我有一个由ajax处理的表单,并使用jQuery验证进行验证。它按预期工作,但是当我在表单字段的模糊上添加字段验证时,它会停止正常工作。它停止通过ajax发布,而只是转到用于处理ajax的php文件。它似乎也没有正确处理文件上传,说有没有一个。在失败的帖子后通过浏览器返回并重新提交然后工作正常。所以我不确定发生了什么。
这是JS:
// highlight input fields on blur - This is what stops it working
$('.input-field').on('focusout', function(){
$(this).parents('form').validate({
onfocusout: function(element) {
this.element(element);
},
onkeyup: false
});
});
// Ajax form submit/validation
$(document).on('click', '.form-submit', function(e){
// Whichever form sent it..
var $thisForm = $(this).parents('form');
// Validate it...
$thisForm.validate({
ignore: '',
rules: {
upload: {
required: true
}
},
submitHandler: function(form) {
var formData = new FormData($thisForm[0]);
// Show the loading spinner
$thisForm.addClass('loading').find('.padded').remove();
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
data: formData,
processData: false,
contentType: false,
url: $thisForm.attr('action'),
success: function(data) {
// When we're done, remove spinner and add the thank you message
$thisForm.parents('aside').addClass('textcenter padded').html(data.message);
$('.loading').removeClass('loading');
}
});
}
});
});
答案 0 :(得分:2)
您的代码......
// highlight input fields on blur - This is what stops it working
$('.input-field').on('focusout', function(){
$(this).parents('form').validate({....
这就是......
// Ajax form submit/validation
$(document).on('click', '.form-submit', function(e){
....
// Validate it...
$thisForm.validate({ ....
.validate()
无法与您的初始化选项一起附加到单个字段。
你完全误解了.validate()
方法的目的。 .validate()
只是在表单上初始化插件的方法。它不是测试方法。测试是自动执行的,因为插件正在捕获按钮的单击以及各种其他事件,以便自动触发。
您绝不会将.validate()
放在focusout
或click
处理程序中。在"焦点关注"时自动触发验证。和"点击"根据此插件的默认值。
您只需要正确初始化它。
$(document).ready(function() { // DOM is loaded
$('.forms').each(function() { // select all forms
$(this).validate({ // initialize plugin on each form
// options // your plugin options
});;
});
});
.validate()
进入DOM ready even处理函数,在页面加载时初始化插件。
当.validate()
一次附加到多个表单时,就像使用类选择器一样,该方法仅适用于第一个匹配的元素。你需要使用jQuery .each()
来解决这个问题。
请参阅以下内容......