我在我的联系表单中使用了 jquery 验证插件,如果表单中有问题,它会返回,但即使条目不正确(例如名称不超过 1 个字符)我也可以提交表单并且它发送包含错误数据的电子邮件。在条目全部正确之前,我怎样才能阻止按钮处于事件状态?
$(document).ready(function() {
var newHTML = '<div class="col-sm-12 text-center" style="color:white; background-color:#6f8595; padding-bottom:15px; border-radius:5px;"><h3>Thank you for your message!<br />We will get back to you as soon as possible!</h3></div>';
$('#myform').validate();
$('.btn').click(function(){
var data = $("#myform").serialize();
$('.form').html('').append(newHTML);
$.post( "includes/sendmail.php", {data});
});
});
最佳答案
像这样:
$(function() {
var newHTML = '<div class="col-sm-12 text-center" style="color:white; background-color:#6f8595; padding-bottom:15px; border-radius:5px;"><h3>Thank you for your message!<br />We will get back to you as soon as possible!</h3></div>';
$('#myform').validate();
$('#myform').on("submit",function(e){
e.preventDefault();
if ($(this).valid()) {
var data = $(this).serialize();
$(this).html(newHTML);
$.post( "includes/sendmail.php", {data});
}
});
});
或者根据 documentation您可以在验证提交处理程序中执行 AJAX 调用 - 如下所示:
$('#myform').validate({
submitHandler: function(form) {
var data = $(form).serialize();
$(form).html(newHTML);
$.post( "includes/sendmail.php", {data});
return false;
}
});
关于javascript - jQuery 验证有效,但如果条目不正确,仍然能够提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37343301/