前阿贾克斯jQuery的表单验证提交 [英] jQuery Form Validation before Ajax submit
问题描述
JavaScript的一点:
$(文件)。就绪(函数()
{
$('#形式)。递交(函数(五)
{
即preventDefault();
变量$形式= $(本);
//检查输入有效
如果(!$ form.valid())返回false;
$阿贾克斯(
{
键入:POST,
网址:'add.php',
数据:$('#形式')序列化()。
成功:函数(响应)
{
$(#答案)的HTML(响应)。
}
});
})
});
HTML位:
<输入类型=文本名称=回答[1]级=需要/>
<输入类型=文本名称=回答[2]级=需要/>
所以这是code我想使用。我们的想法是让我所有的输入验证之前,我把我的形式使用Ajax。我已经试过这众多的版本,但现在每当我结束了,即使形式不完全填写提交。我所有的输入是必需的类。任何人都可以看到我在做什么错了?
另外,我依赖于基于类的要求与PHP产生我输入名字,所以我不能确定什么名字[ID]或输入类型我得到的。
我显示/隐藏问题,正如我在页面。
通过它 <输入类型=按钮ID =下一步的onClick =toggleVisibility('form3')级=下BTN/>
记者:
函数toggleVisibility(newSection)
{
$(部分)不(#+ newSection).hide()。
$(#+ newSection).show();
}
您可以使用 submitHandler
选项。基本上把 $。阿贾克斯
调用这个处理程序中,即与验证安装逻辑颠倒了。
$('#形式')。验证({
...您的验证规则来这里,
submitHandler:功能(形式){
$阿贾克斯({
网址:form.action,
类型:form.method,
数据:$(形式).serialize()
成功:函数(响应){
$('#答案)HTML(响应);
}
});
}
});
在 jQuery.validate
插件将调用提交处理程序,如果验证通过了。
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 bit:
<input type="text" name="answer[1]" class="required" />
<input type="text" name="answer[2]" class="required" />
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?
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();
}
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);
}
});
}
});
The jQuery.validate
plugin will invoke the submit handler if the validation has passed.
这篇关于前阿贾克斯jQuery的表单验证提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!