jQuery 我如何知道我的 input type="file" 是否选择了内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16125255/
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 I know if my input type="file" has content selected
提问by MrMins
i have a simple input file <input type="file" name="file" id="file">
but I'm trying to validate after the post if the input file has content.
我有一个简单的输入文件,<input type="file" name="file" id="file">
但我试图在发布后验证输入文件是否有内容。
I trying with $("#file").val()
but, the dom of the controls is the same always.
我尝试使用$("#file").val()
但是,控件的 dom 始终相同。
回答by multimediaxp
What do you mean by: after the post, do you mean:
你是什么意思:在帖子之后,你的意思是:
-After clicking on a submit buttonbut before posting or submitting?
-点击提交按钮后但在发布或提交之前?
-Or you mean after it has been submitted and the content has reached the server?
- 或者你的意思是在提交并且内容到达服务器之后?
If it is the first case, make sure to return false to the form so it doesn't submit, and you can validate, for example:
如果是第一种情况,请确保向表单返回 false 以便它不会提交,并且您可以进行验证,例如:
<form onsubmit="return false">
or try to return a boolean to the form after calling a validation function on submit:
或尝试在提交时调用验证函数后向表单返回一个布尔值:
<form onsubmit="return validate()">
Then using Jquery validate your data:
然后使用 Jquery 验证您的数据:
function validate(){
valid = true;
if($("#file").val() == ''){
// your validation error action
valid = false;
}
return valid //true or false
}
if you find errors return false, if the data is valid return true. After understanding how it works, ultimately, all of this can be done with Jquery:
如果发现错误返回false,如果数据有效返回true。在了解了它是如何工作的之后,最终这一切都可以用 Jquery 来完成:
HTML:
HTML:
<form id="fileform" action="nextpage.php">
JS:
JS:
$('#fileform').submit(function(){
valid = true;
if($("#file").val() == ''){
// your error validation action
valid = false;
}
return valid
});
Also, if you are checking to see what type of file is being submitted, you can check this post: jQuery - INPUT type=File , Image FileType Validation options?
此外,如果您正在检查正在提交的文件类型,您可以查看这篇文章:jQuery - INPUT type=File , Image FileType Validation options?
If what you want to do is validate the data AFTERsubmitting then you have to code the validation in a server scripting language like PHP.
如果你想要做的是对数据进行验证后,然后提交,你必须代码在服务器脚本语言如PHP验证。
回答by Mohamed Nagy
try to get the value after the form submission like this
尝试像这样在表单提交后获取值
$('#yourform').submit(function(){
var val = $("#file").val();
if(val == ''){
return false;
}
});
回答by m.edmondson
trying to validate after the post
尝试在帖子后验证
This would be something you would do server-sidenot on the client via jQuery. If you tag your question with the server-side language you're using we can then provide you with the help you need.
这将是您将通过 jQuery 在服务器端而不是在客户端上执行的操作。如果您使用您正在使用的服务器端语言标记您的问题,我们可以为您提供所需的帮助。