在我的页面上,我有 3 个完整的表单,每个表单都有自己的提交按钮,每个表单和按钮都有不同的 id。
<form action="" method="post" class="form-horizontal" id="formA">
...
<button id="formASend" type="submit" class="btn"> Submit</button>
</form>
<form action="" method="post" class="form-horizontal" id="formB">
...
<button id="formBSend" type="submit" class="btn"> Submit</button>
</form>
<form action="" method="post" class="form-horizontal" id="formC">
...
<button id="formCSend" type="submit" class="btn"> Submit</button>
</form>
在javascript中,每个提交按钮都有以下逻辑:
$.validator.setDefaults({
debug:true,
errorElement: 'span', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input)
highlight: function (element) { // hightlight error inputs
$(element).closest('.control-group').addClass('error'); // set error class to the control group
},
unhighlight: function (element) { // revert the change dony by hightlight
$(element)
.closest('.control-group').removeClass('error'); // set error class to the control group
}
});
$(function() {
var formA = $('#formA');
// init validator obj and set the rules
formA.validate({
rules: {
...
}
});
formA.submit(function () {
return formA.valid();
});
var formB = $('#formB');
// init validator obj and set the rules
formB.validate({
rules: {
...
}
});
formB.submit(function () {
return formB.valid();
});
var formC = $('#formC');
// init validator obj and set the rules
formC.validate({
rules: {
...
}
});
formC.submit(function () {
return formC.valid();
});
});
第一种形式提交工作正常,其他两种形式无效。我用DOMLint检查了html索引,没有问题。点击事件被触发,表单有效,提交返回true,但不提交。
验证工作正常,仅验证提交的表单。
如何对每个表格应用不同的规则?
可能的解决方案
$.validator.setDefaults({
debug:true,
errorElement: 'span', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input)
highlight: function (element) { // hightlight error inputs
$(element).closest('.control-group').addClass('error'); // set error class to the control group
},
unhighlight: function (element) { // revert the change dony by hightlight
$(element)
.closest('.control-group').removeClass('error'); // set error class to the control group
},
submitHandler: function (form) {
if ($(form).valid()) {
form.submit();
}
}
});
$(function() {
var formA = $('#formA');
// init validator obj and set the rules
formA.validate({
rules: {
...
}
});
var formB = $('#formB');
// init validator obj and set the rules
formB.validate({
rules: {
...
}
});
var formC = $('#formC');
// init validator obj and set the rules
formC.validate({
rules: {
...
}
});
});
添加提交处理程序,将提交事件返回到操作中。