Reputation: 4676
Hi I use jQuery validator for one form. It was working nice until today. I added a new code to the form which adds/remove additional fields to the form (with set classes to "required")..
basic the form is some thing like >
<form name="form" id="form">
<input name="text1" class="required">
<a id="addnew">Add new text</a>
<div id="newitems"></div>
<submit>
</form>
The code I use is
<script type="text/javascript">
$(document).ready(function({ $("#form").validate();
$("#addnew").click(function({
$("#newitems").append('<input class="required" name="newinput">');
}); });
</script>
The idea is that when someone click on the Add new text inside the form is added a new field. My problem is that then the Validator doesn't work on the new field because its already loaded for the form.. How I can set the javascript to check and the new fields?
I haven't copy the exact code of my site because its very long..
This Is the validation plugin - its the most used validator on jquery
Upvotes: 5
Views: 1703
Reputation: 559
You have to bind the event again after loading the dynamic content.
if you are adding dynamic content any of existing not affecting to the new controls. you have to assign the event again after modifing the dom. so call the validator again afer dom modification.
If you want to rebind simply call again
$("#addnew").click(function({
$("#newitems").append('<input class="required" name="newinput">');
});
You can also put it in a function
function rebindit() {
$("#addnew").click(function({
$("#newitems").append('<input class="required" name="newinput">');
});
}
and each time your content changes call rebindit();
Upvotes: 1
Reputation: 804
There is an onchange event in javascript which is triggered when the content of the field changes. You can make use of it on the new field to avail validation for that field as well.
Upvotes: 0
Reputation: 337560
Upon creation of your new form element, you need to inform the validation plugin to check it by adding a rule. Adding the 'required' class to an element only alerts the plugin if the element is present on document load. Try this:
$(document).ready(function({
$("#form").validate();
$("#addnew").click(function({
var input = $("<input />").attr("name", "newinput");
$("#newitems").append(input);
input.rules('add', {'required': true})
});
});
Upvotes: 5
Reputation: 24302
if you are adding dynamic content any of existing not affecting to the new controls. you have to assign the event again after modifing the dom. so call the validator again afer dom modification.
Upvotes: 1