我正在使用 Ajax 和 jQuery 来验证和提交表单中的信息。我遇到的问题是,当我单击提交按钮时,表单会在执行验证检查并显示错误之前立即将信息提交到服务器?
我不确定这里有什么问题,所以任何输入都会很棒!
干杯
$('#submit_second').click(function() {
//remove classes
$('#second_step input').removeClass('error').removeClass('valid');
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var phonePattern = /^\+?[0-9]{0,15}$/ ;
var fields = $('#second_step input[type=text]');
var error = 0;
fields.each(function() {
var value = $(this).val();
if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value))) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='phone' && !phonePattern.test(value) ) ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
//update progress bar
$('#progress_text').html('66% Complete');
$('#progress').css('width','226px');
//slide steps
$('#second_step').slideUp();
$('#fourth_step').slideDown();
} else return false;
});
$('#submit_second').click(function(){
url =$("input#url").val();
yourname =$("input#yourname").val();
email =$("input#email").val();
phone =$("input#phone").val();
//send information to server
var dataString = 'url='+ url + '&yourname=' + yourname + '&email=' + email + '&phone=' + phone;
alert (dataString);
$.ajax({
type: "POST",
url: "#",
data: "url="+url+"&yourname="+yourname+"&email="+email+'&phone=' + phone,
cache: false,
success: function(data) {
console.log("form submitted");
alert("success");
}
});
return false;
});