Reputation: 171
I am having trouble validating a long form that is loaded via AJAX after the document is loaded. Using the standard validation syntax, the validator looks for my form in the document before it exists and therefore gives me an error:
$(document).ready(function(){
$("#mainForm").validate();
});
firebug responds with:
nothing selected, can't validate, returning nothing
I tried putting the $("mainForm").validate();
in a function then calling the function with the onSubmit event from the form but no luck:
function validate() {
$("mainForm").validate();
};
----------
<form id="mainForm" onSubmit="validate();">
...
</form>
Thoughts?
Some additional info for @Chris:
I have a page that is dynamically creating a form based on many different modules. The user picks the module(s) that apply to them then the form updates with that information to fill in. So when the user clicks on a link to load a module the loadSection();
function is called. This is what the loadSection();
function looks like:
function loadSection(id, div, size, frame) {
var url = "loadSection.php?id=" + id + "&size=" + size + "$frame=" + frame;
$.get(url,
function(data){
$(div).append(data);
});
}
If I put the `$(#mainForm).validate();' in the callback of this function, it has the potential to get called every time a new module is inserted. Which may be good, or may be bad, I'm not sure how the validation will take to be called multiple times on the same form, even if the fields of the form have changed.
Thoughts?
Upvotes: 0
Views: 1948
Reputation: 12935
You've likely got the problem right. If the form doesn't exist in the DOM at document.ready(), then nothing will be bound.
Since you're using JQuery, I presume the form is added using the jquery $.ajax (or similar) function. The most straightforward solution would be just to add $("#mainForm").validate();
to the callback function of the AJAX request. If you're not using JQUery ajax, please post the code that's adding the form, and we can help you out further.
Upvotes: 1
Reputation: 171669
Simple mistake in selector "mainform"
is not a valid selector. Add "#" prefix if it is an ID
EDIT: Also notice you have another validate call inline , remove that one
Upvotes: 0
Reputation: 8710
you have to specify the class definition to element as required
for it to validate that particular element in the form. But I guess you are not having it anywhere so its showing like that.
for example if you want to validate the email:
<p>
<label for="cemail">E-Mail</label>
<em>*</em><input id="cemail" name="email" size="25" class="required email" />
</p>
Upvotes: 0