jQuery Validation: Validate dynamicly generated fields only on the first field
Yes, I know this question has been asked a few times before. But I am confused with the answers. I thought I would have to somehow 'refresh' or use live to add the validation each time I add a new input field.
Also I checked out the demo and I think I am missing something. I don't really see any code that adds validation each time a new field gets added.
This is a simplifie开发者_运维问答d version of my code:
$(function(){
$('#testform').validate();
var input1 = $('<input type="text" class="required" />'):
var input2 = $('<input type="text" class="required" />'):
var input3 = $('<input type="text" class="required" />'):
$('#testform').append(input1)
.append(input2)
.append(input3);
});
My html looks something like this:
<form id='testform'>
<input type='submit' value='submit' />
</form>
For some reason validation only works on the first element. If you fill in text it works on the onblur event. But the form will submit once the first input field has text.
Actually I think just found the answer while typing this but I'll add this question anyway in case others run into the same problem. If this is a problem I'll remove it right away.
For the jQuery validation to work you need to add the name attribute.
So it should be:
$(function(){
$('#testform').validate();
var input1 = $('<input name="one" type="test" class="required" />'):
var input2 = $('<input name="two" type="test" class="required" />'):
var input3 = $('<input name="thr" type="test" class="required" />'):
$('#testform').append(input1)
.append(input2)
.append(input3);
});
On the jQuery validation page:
The name attribute is required for input elements, the validation plugin doesn't work without it. Usually name and id attributes should have the same value.
http://docs.jquery.com/Plugins/Validation/Reference
The first thing I would do is assign a name and ID to each of your text elements and see if that makes a difference.
Also I think you have to put your $('#testform').validate(); inside a $().ready(function() { } block. This forces jQuery to not start the form validation until the page is ready (and completely rendered by the browser)
精彩评论