如果表单字段为空,则使用ajax阻止表单提交

Tom*_*sen 3 javascript ajax jquery

我有一个简单的形式有些麻烦.如果字段为空,我似乎无法阻止表单提交.有没有一种简单的方法来检查字段是否为空,然后阻止表单提交?

这是我的html表单:

<form method="post" name="simpleForm" id="simpleForm" action="handler.php">
<fieldset>
    <legend>Info</legend>
            <p><label for="name">Name</label><br>
            <input id="name" name="name" class="text" /></p>
            <p><label for="email">Email</label><br>
            <input id="email" name="email" class="text" /></p>

    <legend>Questions</legend>
            <p><label for="qs_1">Question 1</label><br>
            <input id="qs_1" name="qs_1" class="text" /></p>
            <p><label for="qs_2">Question 2</label><br>
            <input id="qs_2" name="qs_2" class="text" /></p>
            <p><label for="qs_3">Question 3</label><br>
            <input id="qs_3" name="qs_3" class="text" /></p>

</fieldset>             

<p><input type="submit" name="submit" value="Send" id="sub_btn" /></p>
</form>
Run Code Online (Sandbox Code Playgroud)

这是我的javascript:

$("form#simpleForm").submit(function() {

        var name     = $('#name').attr('value');
        var email    = $('#email').attr('value');
        var qs_1     = $('#qs_1').attr('value');
        var qs_2     = $('#qs_2').attr('value');
        var qs_3     = $('#qs_3').attr('value');



            $.ajax({
                type: "POST",
                url: "handler.php",
                data: "name="+ name +"& email="+ email +"& qs_1="+ qs_1 +"& qs_2="+ qs_2 +"& qs_3="+ qs_3,
                success: function(){
                    $('form#simpleForm').hide(function(){$('div.success').fadeIn();});

                }
            });
        return false;
});
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 9

使用e.preventDefault()取消表单提交.如果您不想发送AJAX呼叫,请添加条件检查.另外,使用.val()而不是.attr("value").

$("form#simpleForm").submit(function(ev) {
    ev.preventDefault();

    var name     = $('#name').val();
    var email    = $('#email').val();
    var qs_1     = $('#qs_1').val();
    var qs_2     = $('#qs_2').val();
    var qs_3     = $('#qs_3').val();

    //This condition will only be true if each value is not an empty string
    if(name && email && qs_1 && qs_2 && qs_3){
        $.ajax({
            type: "POST",
            url: "handler.php",
            data: "name="+ name +"& email="+ email +"& qs_1="+ qs_1 +"& qs_2="+ qs_2 +"& qs_3="+ qs_3,
            success: function(){
                $('form#simpleForm').hide(function(){$('div.success').fadeIn();});

            }
        });
     }
     return false; //IE
});
Run Code Online (Sandbox Code Playgroud)