文件输入JS onchange,onclick不触发

File input JS onchange, onclick not firing

我正在尝试使用已选择的文件名填充文本类型的输入。根据我的阅读,有时您必须将值设置为“”或 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

None 其中似乎是我的问题...

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

给你。您可以去掉 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")

引用的元素

Uncaught TypeError: Cannot set property 'onchange' of null at :2:48