How to check input file is empty, and also display

2019-03-18 07:34发布

I have got an input file upload , need to check which file is uploaded / if no file is selected by the client using jquery.

<input type="file" name="files" id="file1" style="color:White" />
<input type="submit" value="Create" />

The check should trigger when submit is clicked.

4条回答
在下西门庆
2楼-- · 2019-03-18 07:53

This demo works in IE9 + Chrome:

http://jsfiddle.net/brdFq/

using Jquery, you get the val();

a quick implementation here:

function hasFile(selector){
    //if there is a value, return true, else: false;
    return $(selector).val()? true: false;
}
查看更多
不美不萌又怎样
3楼-- · 2019-03-18 08:11

Have you made any attempt at doing this?

$('input[type="file"]').val()
查看更多
唯我独甜
4楼-- · 2019-03-18 08:15

Testing for...

$('#file1')[0].files.length == 0

...is working for me in Chrome. The jQuery is actually not even necessary as the raw HTML element (returned by the [0] on the jQuery object) gives access to the files list.

查看更多
小情绪 Triste *
5楼-- · 2019-03-18 08:17

See the sample I have created:

http://jsfiddle.net/G7xke/


<form>
<input type="file" name="files" id="file1" style="color:White" />
<input type="submit" value="Create" />
</form>
<button value="check" id="check" name="check" >check</button>

And JavaScript:

$("#check").click(function(){
    var fileName = $("#file1").val();
    if(fileName.lastIndexOf("png")===fileName.length-3)
        alert("OK");
    else
        alert("Not PNG");
})
查看更多
登录 后发表回答