【问题标题】:File input JS onchange, onclick not firing文件输入JS onchange,onclick不触发
【发布时间】:2017-06-03 03:45:41
【问题描述】:

我正在尝试使用已选择的文件名填充文本类型的输入。根据我的阅读,有时您必须将值设置为 "" 或 null onClick 然后 onchange 设置占位符。

我尝试了许多不同的变化,但它似乎并没有触发。我忽略了什么?

我的非常基本的例子....

<script type="text/javascript">
    getElementById("upFile").onClick = function(){
        this.value = "";
    }

    getElementById("upFile").onchange = function(){
        getElementById("uploadName").value = this.value;
    }
</script>


    <input type="text" name="uploadName" id="uploadName" placeholder="Attachment Title">
    <input type="file" id="upFile" name="upFile" enctype="multipart/form-data"><br>

我读过的

Changing the placeholder text based on the users choice

Change placeholder text

Upload files using input type="file" field with .change() event not always firing in IE and Chrome

HTML input file selection event not firing upon selecting the same file

这些似乎都不是我的问题...

【问题讨论】:

  • 尝试将脚本标签移到 html 之后
  • 检查您的浏览器控制台是否有错误。除非您另有安排,否则为document.getElementById()
  • @Brian 我刚试过,没有运气。
  • @Brian 但是我不认为这是我在 html 上方有一个工作脚本做不同事情的问题
  • 您是否查看了浏览器的检查器以查看出现了哪些错误?

标签: javascript file-io asp-classic onclick onchange


【解决方案1】:

给你。您可以摆脱 onclick 事件侦听器,并注意更改。文件上传元素创建一个文件数组,您可以像这样访问它:

<input type="text" name="uploadName" id="uploadName" placeholder="Attachment Title">
<input type="file" id="upFile" name="upFile" enctype="multipart/form-data">

<script>
    document.getElementById("upFile").onchange = function(){
        // single file selection, get the first file in the array
        document.getElementById("uploadName").value = this.files[0].name; 
    }
</script>

仅供参考: 如果脚本标签在元素之前,就会发生这种情况。一旦读取它就会运行脚本并说它找不到document.getElementById("upFile")引用的元素

未捕获的类型错误:无法将属性“onchange”设置为 null 在:2:48

【讨论】:

  • 啊,我没有意识到它将值存储在一个数组中。谢谢。
  • @gflynn94 没问题
【解决方案2】:

您缺少 document.getElementById 并且 onClick 应该是 onclick

【讨论】:

    猜你喜欢
    • 2017-07-10
    • 2018-10-22
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 2013-11-07
    • 2017-07-19
    相关资源
    最近更新 更多