jQuery Validation plugin with live "click"
I have have a site where the user can alter the page content using jquery load
. In each page content I have a form which I validate with jquery validation plugin
$("#form-create").validate({
submitHandler: function(form) {
var name = $("#name").val();
save(name);
return false;
}
});
I have noticed that all jquery click
functions only work until I change the page content but I solved it with replacing the click
with live "click"
. Though the 开发者_JAVA技巧same problemm occurs with the above validation. How come using click
works until I altered the page content and live "click"
solves the problem? OR how can I use the validation plugin with live "click"
,which will solve the problem, but not explain it to me :)
The reason that live click solves your problem is that the elements didn't originally exist on your DOM, so using "live" means it's a live click regardless due to it refreshing as new elements arrive on the DOM. The default events only use the first DOM that was loaded.
If you want to check validate through the live click event then you should use something like this:
$('.submitButton').live("click", function() {
$("#form-create").validate({
submitHandler: function(form) {
var name = $("#name").val();
save(name);
return false;
}
});
});
Hope this helps, it was a little difficult as you didn't specify which validation plugin you're using, however, whatever the plugin this should work assuming you wish to call the validation on the submit button click event.
when you bind a set of elements, say $("div.clickable")
, with an event, the set is resolved with the DOM at the time of the execution of the $() function. All succeeding elements (appearing after that moment) won't be bound because they didn't belongs to the original set
Live does exactly this : it refreshes the original set as new element appears, then new elements are bound as they appear in the DOM
Unfortunately, there is no load event in live, although this is being asked for quite some time.
You can go around this by placing a callback function in your ajax calls. This can be done globally using global ajax event handlers:
$('#contentDiv').ajaxComplete(function() {
$("#form-create").validate(validateOptions);
});
精彩评论