Reputation: 23
I am trying to add some validation rules on an input created from html literals.
This is my fiddle: http://jsfiddle.net/idoxobi/HW4xY/1/
Html:
<form id='form' method='post' >
<div id='details'>
</div>
<a id='Add' href='javascript:void()'>Add</a>
<br />
<input type='submit' />
</form>
JavaScript:
$(document).ready(function() {
$('#form').validate();
var input = "<input type='text' class='item' name='item' />";
$('#Add').click(function() {
$('#details').append(input+'<br />');
$('#details input:last').rules('add', {
required: true
});
});
})
It seems to recognize the rule just in the first element, but the others pass without validation.
Is the first time I use this plug-in, but in the forums everyone says this should work just fine.
Any suggestions?
Upvotes: 1
Views: 7234
Reputation: 6612
Its because input field name is same for each, and it has been fixed by @YD1m, my method is as below:
$(document).ready(function() {
$('#form').validate();
var counter = 0;
$('#Add').click(function() {
counter++;
$('#details').append("<input type='text' class='item required' name='item_" + counter + "' />" + '<br />');
});
});
Upvotes: 0
Reputation: 5895
check this:
html:
<form id='form' method='post' >
<div id='details'>
</div>
<a id='Add' href='#'>Add</a>
<br />
<input type='submit' />
</form>
js:
$(document).ready(function() {
$('#form').validate();
var i = 0;
$('#Add').click(function() {
var input = "<input type='text' class='item' name='item"+ i++ +"' />";
$('#details').append(input+'<br />');
$('#details input:last').rules('add', {
required: true
});
return false;
});
});
Upvotes: 1