JQuery: Binding the .validate plugin to .live
I need to bind the jQuery validate plugin to forms that I generate on the fly. As far as I know .live()
is the only way to do this in jQuery. It doesn't seem to work, at least the way I'm trying. I think th开发者_运维技巧is is do'able and it's just eebkac!
This works Fine:
$("form#form_CreateUser").validate({
submitHandler: function(form) {
// do other stuff for a valid form
UserSubmit();
}
});
This generates syntax errors:
$("form#form_CreateUser").live('validate', function() {
submitHandler: function(form) {
// do other stuff for a valid form
UserSubmit();
}
});
This doesn't work because you've misunderstood how validate
works. It looks like event handler functions like click
, but it actually is not.
click
is a shortcut for bind('click', fn)
. validate
does not work by using bind
. Since live
is effectively a way of making bind
calls work on elements that don't yet exist, it doesn't work with validate
.
The easiest way of doing this is to make a function that calls validate
and call that function every time you insert new content. For instance, if you are inserting the form using AJAX, you could use the ajaxComplete
function:
function setupValidate() {
$("form#form_CreateUser").validate({
submitHandler: function(form) {
// do other stuff for a valid form
UserSubmit();
}
});
}
$(document).ajaxComplete(setupValidate); // after every AJAX request
setupValidate(); // right now
精彩评论