当输入字段为空时,使用jQuery防止表单提交 [英] Using jQuery to prevent form submission when input fields are empty

查看:439
本文介绍了当输入字段为空时,使用jQuery防止表单提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案应该非常简单。我试图阻止表单在输入框中找不到值时正确提交。这里是我的JSFiddle: http://jsfiddle.net/nArYa/7/



//标记

 < 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;
    }
});

Updated fiddle

这篇关于当输入字段为空时,使用jQuery防止表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆