admin管理员组文章数量:1334373
I'm using JavaScript to validate an uploading form, one of the conditions is to check if any file has been selected. I thought this would be simple, but I can't get it to work. Is this code invalid? The var file works with other conditions so it's not that
var file = document.getElementById('file');
if(file.value =="") {
alert("no file selected")
return false;
}
<input name="uploaded" type="file" id="file" />
I'm using JavaScript to validate an uploading form, one of the conditions is to check if any file has been selected. I thought this would be simple, but I can't get it to work. Is this code invalid? The var file works with other conditions so it's not that
var file = document.getElementById('file');
if(file.value =="") {
alert("no file selected")
return false;
}
<input name="uploaded" type="file" id="file" />
Share
Improve this question
edited Dec 10, 2020 at 19:55
Zorayr
25k8 gold badges146 silver badges138 bronze badges
asked Jan 14, 2013 at 22:50
user1559811user1559811
4494 gold badges12 silver badges26 bronze badges
3
- I vaguely remember not being able to get the value of a file input for security reasons. I may be wrong. – Popnoodles Commented Jan 14, 2013 at 22:52
- Are you calling document.getElementById('file') before the file input tag exists? – beezir Commented Jan 14, 2013 at 22:54
- Ok, I have put that condition first, and now it works, problem solved – user1559811 Commented Jan 14, 2013 at 23:10
1 Answer
Reset to default 10You can use the following example:
var fileInput = document.getElementById('file');
fileInput.onchange = function () {
var input = this.files[0];
if (input) {
//process input.
} else {
alert("Please select a file.");
}
};
Hope this helps.
本文标签: htmlHow to determining if a file has been selected in JavaScriptStack Overflow
版权声明:本文标题:html - How to determining if a file has been selected in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742239058a2438570.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论