简体   繁体   English

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

[英]Prevent form submit with ajax if form fields are empty

Im having some trouble with a simple form.我在使用简单的表格时遇到了一些麻烦。 I can't seem to prevent the form from submiting if the fields are empty.如果字段为空,我似乎无法阻止表单提交。 Is there an easy way to check if the fields are empty, and then prevent the form submitting?有没有一种简单的方法来检查字段是否为空,然后阻止表单提交?

Here is my html form:这是我的 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>

Here is my javascript:这是我的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;
});

Use e.preventDefault() to cancel the form submission.使用e.preventDefault()取消表单提交。 If you want to not send an AJAX call, add a condition check.如果不想发送 AJAX 调用,请添加条件检查。 Also, use .val() instead of .attr("value") .此外,使用.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
});

In a general sense if you return false from the submit handler it will prevent the form being submitted in the standard (non-ajax) way, but I see you are already doing this - which you need to if you want to submit it via ajax instead or it will make the ajax call and submit normally.一般来说,如果您从提交处理程序返回 false,它将阻止以标准(非 ajax)方式提交表单,但我看到您已经这样做了 - 如果您想通过 ajax 提交它,则需要这样做相反,它会进行ajax调用正常提交。

So all you need for your validation is to put an if test that only makes the $.ajax() call if validation passes:因此,您验证所需的只是放置一个 if 测试,该测试仅在验证通过时才进行$.ajax()调用:

if (name != "" && etc...) {
   $.ajax({ /* your existing ajax code here */ });
}

EDIT: you can also test that there are no blank fields with a single jQuery selector:编辑:您还可以使用单个 jQuery 选择器测试是否没有空白字段:

if ($("#simpleform :text[value='']").length === 0) {
   $.ajax({ /* your existing ajax code here */ });
}

Here is a very simple function to make a form invalid if any of the inputs is empty:这是一个非常简单的函数,可以在任何输入为空时使表单无效:

     function validateForm(data){
         var is_valid = true;
         $.each(data, function(id, obj) {
             if(obj.value === "") {
                 is_valid = false;
             }
         });   
         return is_valid;         
     }

The data argument should be a json serialized form. data参数应该是一个 json 序列化形式。

Usage:用法:

    var form_data = $( "#my_form" ).serializeArray();
    var is_valid = validateForm(form_data);

    if(is_valid === true){
        // your ajax code
    }

Just have an if check before making ajax request:在发出 ajax 请求之前只需检查一下:

if(name != '' && email != '' ...)
{
//send request is true
$.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();});

                }
            });

}

else{
return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM