最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to determining if a file has been selected in JavaScript? - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 10

You 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.

发布评论

评论列表(0)

  1. 暂无评论