Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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()) === "") ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
604 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...