如何检查输入文件是否为空,并在使用 jquery 选择 png 格式时显示警报
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6682662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check input file is empty, and also display an alert if png format is selected using jquery
提问by Mr A
I have got an input file upload , need to check which file is uploaded / if no file is selected by the client using jquery.
我有一个输入文件上传,需要检查哪个文件被上传/如果客户端没有使用 jquery 选择文件。
<input type="file" name="files" id="file1" style="color:White" />
<input type="submit" value="Create" />
The check should trigger when submit is clicked.
单击提交时应触发检查。
回答by Aliostad
See the sample I have created:
请参阅我创建的示例:
<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:
和 JavaScript:
$("#check").click(function(){
var fileName = $("#file1").val();
if(fileName.lastIndexOf("png")===fileName.length-3)
alert("OK");
else
alert("Not PNG");
})
回答by Adam Hopkinson
Have you made any attempt at doing this?
你有没有尝试过这样做?
$('input[type="file"]').val()
回答by SteveShaffer
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.
...在 Chrome 中为我工作。实际上甚至不需要 jQuery,因为原始 HTML 元素(由[0]
jQuery 对象上的返回)可以访问文件列表。
回答by Fallenreaper
This demo works in IE9 + Chrome:
此演示适用于 IE9 + Chrome:
http://jsfiddle.net/brdFq/
using Jquery, you get the val();
使用 Jquery,你会得到 val();
a quick implementation here:
在这里快速实现:
function hasFile(selector){
//if there is a value, return true, else: false;
return $(selector).val()? true: false;
}