当输入字段为空时,使用jQuery防止表单提交 [英] Using jQuery to prevent form submission when input fields are empty
问题描述
//标记
< form action =method =postname =formid = 形式 >
< input type =textplaceholder =Your email *name =emailid =email>
< input type =textplaceholder =Your name *autocomplete = off name =nameid =user_name
< button type =submitid =signupvalue =注册我!>注册< /按钮>
< / form>
// jQuery
if($ .trim($(#email,#user_name).val())===){
$('#form')。submit(function e){
e.preventDefault();
alert('你没有填写任何一个字段');
})
}
正如您在JSFiddle中看到的那样,问题是当我在两个字段中输入内容时,弹出警报框STILL。我很难弄清楚为什么。在
if($。trim($#email,#user_name)。val())===)中是否有错误?
有两件事,#1检查空字段应该发生在每次提交尝试时,#2您需要单独检查每个字段
$($。$ $ $ $ $ $ $ $ $ $ $ $'$ $ $ $ $''''')。 ).val())===|| || .trim($(#user_name).val())===){alert('您没有填写字段');
返回false;
}
});
The solution should be pretty straightforward. I'm trying to prevent the form from submitting properly when no value is found within the input boxes. Here's my JSFiddle: http://jsfiddle.net/nArYa/7/
//Markup
<form action="" method="post" name="form" id="form">
<input type="text" placeholder="Your email*" name="email" id="email">
<input type="text" placeholder="Your name*" autocomplete=off name="name" id="user_name"
<button type="submit" id="signup" value="Sign me up!">Sign Up</button>
</form>
//jQuery
if ($.trim($("#email, #user_name").val()) === "") {
$('#form').submit(function(e) {
e.preventDefault();
alert('you did not fill out one of the fields');
})
}
As you can see in the JSFiddle, the problem is that when I type something into both fields, the alert box STILL pops up. I'm having a hard time figuring out why. Is there something wrong within my if($.trim($"#email, #user_name").val()) === "") ?
Two things, #1 the check for empty fields should happen on every attempt of submit, #2 you need to check each field individually
$('#form').submit(function() {
if ($.trim($("#email").val()) === "" || $.trim($("#user_name").val()) === "") {
alert('you did not fill out one of the fields');
return false;
}
});
这篇关于当输入字段为空时,使用jQuery防止表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!