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.