I have a form where a user can add the items he intends to buy/sell. The corresponding validation rules that I have is as follows:
rules: {
'items[][name]': {
required: true
},
'items[][description]': {
required: true
},
'items[][rate]': {
required: true,
number: true
},
'items[][quantity]': {
required: true,
number: true
}
}
errorPlacement: function (error, element) {
error.appendTo('#' + element.attr('id') + '_error');
}
Now, user also has the ability to add new items to the form. For that, I clone the first row and append it to the last. The corresponding code is as follows:
var $clone = original.clone().removeAttr('id'); // original is the initial first row of items
$clone.find(':text') // get the text inputs
.val('') // reset their values
.removeClass('error'); // remove the error classes if any
/*
* I have an error span corresponding to each input where I display the errors.
* Here, i get the input and span elements, split them in two groups, then
* add a random seed to each of them to get a unique id to be used by jQuery errorHandler to place the error
*/
var $formElements = $clone.find('input:text, span'),
$even = $formElements.filter(':even'),
$odd = $formElements.filter(':odd');
for (var i = 0; i < $even.length; i++) {
var idParts = $($even[i]).attr('id').split('__');
var seed = Date.now();
$($even[i]).attr('id', idParts[0] + seed + '_' + idParts[1]);
$($odd[i]).attr('id', idParts[0] + seed + '_' + idParts[1] + '_error');
}
My Issues are:
-> Only the first item row, that is created statically, is validated.
I know jQuery validator needs a unique name for each field. But, in this case, I need an array of items. Anyway, even the newly created item fields have the same name, so should not they be validated automatically?
If not, then what is the work around by maintaining an array of items??
Thanks in advance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…