Ajax 提交前的 jQuery 表单验证 [英] jQuery Form Validation before Ajax submit
问题描述
JavaScript 位:
JavaScript bit:
$(document).ready(function()
{
$('#form').submit(function(e)
{
e.preventDefault();
var $form = $(this);
// check if the input is valid
if(! $form.valid()) return false;
$.ajax(
{
type:'POST',
url:'add.php',
data:$('#form').serialize(),
success:function(response)
{
$("#answers").html(response);
}
});
})
});
HTML 位:
<input type="text" name="answer[1]" class="required" />
<input type="text" name="answer[2]" class="required" />
这是我尝试使用的代码.这个想法是在我使用 Ajax 发送表单之前验证我的所有输入.我现在已经尝试了很多版本,但每次我最终都会提交,即使表格没有完全填写.我所有的输入都是必需的"类.谁能看到我做错了什么?
So this is the code I am trying to use. The idea is to get all my inputs validated before I send my form with Ajax. I've tried numerous versions of this now but every time I end up with submitting even though the form is not entirely filled out. All my inputs are of the "required" class. Can anyone see what I am doing wrong?
此外,我依赖于基于类的要求,因为我的输入名称是用 php 生成的,所以我永远无法确定我得到的是什么名称 [id] 或输入类型.
Also, I depend on class-based requirements as my input names are generated with php so I can never be sure what name[id] or input types I get.
我在页面"中浏览时显示/隐藏问题.
I show/hide questions as I go through it in "pages".
<input type="button" id="next" onClick="toggleVisibility('form3')" class="next-btn"/>
JS:
function toggleVisibility(newSection)
{
$(".section").not("#" + newSection).hide();
$("#" + newSection).show();
}
推荐答案
您可以使用 submitHandler
选项.基本上将 $.ajax
调用放在此处理程序中,即使用验证设置逻辑将其反转.
You could use the submitHandler
option. Basically put the $.ajax
call inside this handler, i.e. invert it with the validation setup logic.
$('#form').validate({
... your validation rules come here,
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
$('#answers').html(response);
}
});
}
});
如果验证通过,jQuery.validate
插件将调用提交处理程序.
The jQuery.validate
plugin will invoke the submit handler if the validation has passed.
这篇关于Ajax 提交前的 jQuery 表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!