Dynamic Form validation (not just the fields)
I'm trying to figure out how to do dynamic form validation with jquery, and jquery's validation plugin. I'm fairly new to jquery, and JS in general.
I've figured out how to get the validation to occur when I click submit (using the submitHandler). However I need to POST via ajax, not the native way. So I need to preventDefault, and I don't seem to be able to. The native way to me is when you click submit, the action occurs. I don't want the action to occur as I'm attempting to do it via $.ajax({...});.
If I put the validation in the $('#form').live('click', function(e) {...}), I can now post via ajax, however validation doesn't occur. I've got everything inside the $(document).ready(function() {...};.
How can I get a dynamic form validated inside the live('click') method? I've tried to call validate() when I add the form. I add an entire form via a click on an object, and append to a child object.
Either way (in the submitHandler, or by using live('click')) is fine by me, but I can't seem to figure out either way.
Hopefully 开发者_如何学编程that's enough information, but if not I'll be happy to provide more. A small snippet of the submitHandler below.
$("#form-" + $(this).attr('id')).validate({
submitHandler: function(form) {
this.preventDefault();
// My ajax function below (submitForm);
submitForm(this);
alert('wee');
}
You're not using the submitHandler correctly. Try this:
$("#myform").validate({
submitHandler: function(form) {
form.submit();
}
});
And then override the submit function for the form:
$('#myform').submit(function() {
$.post(url, $(this).serialize(), function(response) {
//do something with the AJAX response
});
return false;
});
The return false; at the end will prevent the default form submission.
Have you had a look at jQuery (ajax) form plugin?
精彩评论