[英]jQuery .validate() will not work on dynamically created table rows
我正在使用 jQuery 验证插件来确保我的表中的所有输入都在 0 到 10 之间。每个表行都是由 JS 动态创建的,这是我的 html 表和用于添加表行的 JS:
<form>
<table id="lineItemTable">
<tbody>
<tr>
<td>
<input type="text" name='gross' class="gross"/>
</td>
<td>
<input type="text" name='tare' class="tare"/>
</td>
</tr>
</tbody>
</table>
<p id="add">add row</p>
</form>
$("#add").click(function() {
var newRow = $('#lineItemTable tbody>tr:last').clone(true).insertAfter('#lineItemTable tbody>tr:last');
newRow.find('.gross').val('');
newRow.find('.tare').val('');
return false;
});
这是我的 jQuery 验证:
$("form").validate({
rules: {
gross: {
range: [0, 10]
},
tare: {
range: [0, 10]
}
},
submitHandler: function() {
var tableObj = $('table tbody tr').map(function(i) {
var row = {};
$(this).find('td').each(function(i) {
row[rowName] = $(this).find("input, select").val();
});
return row;
}).get();
$.ajax({
//code omitted
});
}
});
我的目标是使用此验证来确保每个表行值介于 0 和 10 之间,以便我可以通过$.ajax
提交所有数据。
我现在遇到的问题是它只会阻止第一个表行发生 ajax 调用。 只要第一个表行遵循验证规则,任何具有无效数据的动态创建的表行都会以某种方式通过 ajax 发送。
有人可以帮我解决这个问题吗?
我解决了这个问题,但显然经过大量研究后,这似乎是一个奇怪的问题。
事实证明,我必须修改jquery.validate.js
库才能使其工作。我猜该库在验证子元素时没有提供足够的支持。
在checkForm
,更改以下代码:
checkForm: function() {
this.prepareForm();
return this.valid();
},
到:
checkForm: function() {
this.prepareForm();
for ( var i = 0, elements = ( this.currentElements = this.elements() ); elements[ i ]; i++ ) {
if(this.findByName(elements[i].name).length!=undefined &&this.findByName(elements[i].name).length>1){
for(var count=0; count<this.findByName(elements[i].name).length;count++){
this.check(this.findByName(elements[i].name)[count]);
}
}else{
this.check(elements[i]);
}
return this.valid();
}
},
添加行后尝试重新初始化验证。 为避免代码重复,您可以将其包装在一个函数中:
function initValidation() {
$("form").validate({
rules: {
gross: {
range: [0, 10]
},
tare: {
range: [0, 10]
}
},
submitHandler: function() {
var tableObj = $('table tbody tr').map(function(i) {
var row = {};
$(this).find('td').each(function(i) {
row[rowName] = $(this).find("input, select").val();
});
return row;
}).get();
$.ajax({
//code omitted
});
}
});
}
$("#add").click(function() {
var newRow = $('#lineItemTable tbody>tr:last').clone(true).insertAfter('#lineItemTable tbody>tr:last');
newRow.find('.gross').val('');
newRow.find('.tare').val('');
initValidation();
return false;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.