当输入字段为空时,使用jQuery来阻止表单提交

LNA*_*LNA 17 javascript forms jquery

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

//标记

<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>
Run Code Online (Sandbox Code Playgroud)

// jQuery的

if ($.trim($("#email, #user_name").val()) === "") {
    $('#form').submit(function(e) {
        e.preventDefault();
        alert('you did not fill out one of the fields');
    })
} 
Run Code Online (Sandbox Code Playgroud)

正如您在JSFiddle中看到的那样,问题是当我在两个字段中输入内容时,会弹出警告框STILL.我很难搞清楚原因.在我的 if($ .trim($"#email,#user_name").val())==="")中是否有问题?

koa*_*dev 31

两件事,#1检查空字段应该在每次提交尝试时发生,#2你需要单独检查每个字段

$('#form').submit(function() {
    if ($.trim($("#email").val()) === "" || $.trim($("#user_name").val()) === "") {
        alert('you did not fill out one of the fields');
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)

更新了小提琴


Eln*_*naz 7

HTML5:在输入标签中 使用必需的

  • 布尔属性。

  • 提交表格之前必须填写输入字段。

  • 适用于文本、搜索、网址、电话、电子邮件、密码、日期选择器、数字、复选框、收音机和文件。

    <input required type='text'...>
    
    Run Code Online (Sandbox Code Playgroud)

w3schools 提示


Man*_*ntz 6

您的检查在页面加载时发生.提交表单时需要检查字段.

$('#form').submit(function(e) {
    if ($.trim($("#email, #user_name").val()) === "") {
        e.preventDefault();
        alert('you did not fill out one of the fields');
    }
});
Run Code Online (Sandbox Code Playgroud)