I have a form which I want to validate using the jQuery Validation plugin. I currently have an issue with input element with array (name="inputname[]"
) which are created dynamically with jQuery .on()
. Let me explain the issue:
- There is a form, with one input text exist named
name[]
. - There is a button to add more input texts, and this element executed with .on(). I clicked 2 or 3 times so there will be more than 1 input texts.
- I click submit, the form is correctly validate but it is only validate the first created array element and not the another element.
For full code I created a jsfiddle here: http://jsfiddle.net/ThE5K/4/
jQuery:
$(document).ready(function () {
// MODE 1
// With [] or array name <<<< this one is not working
$("#addInput").on('click', function () {
$('#inputs').append($('<input class="comment" name="name[]" />'));
});
/* MODE 2
Without [] or array name <<<< this one is working
var numberIncr = 1;
$("#addInput").on('click', function () {
$('#inputs').append($('<input class="comment" name="name' + numberIncr + '" />'));
numberIncr++;
});
*/
$('form.commentForm').on('submit', function (event) {
$('input.comment').each(function () {
$(this).rules("add", {
required: true
})
});
event.preventDefault();
console.log($('form.commentForm').valid());
})
$('form.commentForm').validate();
});
HTML:
<form class="commentForm">
<div id="inputs"></div>
<input type="submit" />
<span id="addInput">add element</span>
</form>
I create two modes inside them, the working one (dynamic input text without array name) and the not working one (dynamic input text with array name).
I have been going though those solution but unfortunately no one of them worked:
- jquery validate add rules for an array input
- jquery validate is not working with dynamic content
- jQuery validate dynamic input array
Please help.