0

I've got a form with a pretty simple validation snippet as well as a simple AJAX call, except when I try to put the two together I'm running into problems. If I put the validation snippet ahead of the AJAX call the validation works but the AJAX call simply does not submit. If I put the AJAX call ahead of the validation the AJAX call works and the validation doesn't. I'm really lost and been banging my head for hours over this one. Any help is greatly appreciated!

$("#headerForm").submit(function(){

    var validate = true;      
    $("#headerForm :input").each(function(){                   
        var $this = $(this);                           
        if(this.id == "phoneNumber" && $this.val().length < 10 ){     
            alert("Please enter a valid phone number");
            validate = false;
            return false;        
        } else if(!this.value.length){           
            alert("field is required");
            validate = false;
            return false;  
        }           
    });
    return validate;

var name = $("#name").val();
    var phone = $("#phone").val();

    var dataString = 'name='+ name + '&phone=' + phone; 

    $.ajax({  
      type: "POST",  
      url: "/bin/headerForm",  
      data: dataString,  
      success: function() {  
        $('#headerForm').html("<div id='message'>Thank you</div>");  
      }  
    });  
    return false; 
 });
4

1 回答 1

2

最佳实践是将验证代码移动到一个函数中,然后在提交处理程序中调用它:

function validateForm() {
    var validate = true;
    $("#headerForm :input").each(function () {
        var $this = $(this);
        if (this.id == "phoneNumber" && $this.val().length < 10) {
            alert("Please enter a valid phone number");
            validate = false;
            return false;
        } else if (!this.value.length) {
            alert("field is required");
            validate = false;
            return false;
        }
    });
    return validate;
}

然后提交处理程序:

$("#headerForm").submit(function () {

    if (validateForm()) {
        var name = $("#name").val();
        var phone = $("#phone").val();

        var dataString = 'name=' + name + '&phone=' + phone;

        $.ajax({
            type: "POST",
            url: "/bin/headerForm",
            data: dataString,
            success: function () {
                $('#headerForm').html("<div id='message'>Thank you</div>");
            }
        });
    }
    return false;
});
于 2013-05-13T21:04:42.707 回答