Reputation: 756
I created a JSFiddle. I am dynamically adding a div containing an input element (in real app there are multiple fields). When I click Submit, it just validates the first and not dynamically added HTML elements. I am making sure the dynamic elements have unique ids.
Any thoughts?
$('#submit').click(function (e) {
e.preventDefault();
validator = $("#myForm").validate({
rules: {
name: "required"
}
});
$("#myForm").valid();
});
Update:- I noticed something peculiar. After I add a new input element, and then focused on this new input and click submit, I can see in firebug, that jquery automatically adds a "class=error" to this input tag w/o showing the error message. And if i try writing something to the second input, it removes the error message from the first.
Upvotes: 2
Views: 1916
Reputation: 6086
Changing your markup to this (your submit button was outside of the form tag)
<form id="myForm">
<div id="section">
<input type="text" name="name" class="required"/>
</div>
<input type="button" id="add" value="add" />
<input type="submit" id="submit" value="submit" />
</form>
and inside your jQuery onready you have this
var count = 0;
$("#myForm").validate();
$('#add').on('click', function () {
var section = $('#section').clone(false).attr('id', function () {
return 'section' + (count);
});
section.find('input').attr('name', function () {
return 'name' + (count);
});
section.find('label').attr('for', function () {
return 'name' + (count);
});
section.insertAfter('#section');
count++;
});
This gives you what you need:
Upvotes: 2