I am using the jquery validate plugin to validate and submit a form on my page which has multiple submit buttons to run different functions.
One submit button runs using the $post method while the other uses the standard action method.
(Please stick with me if my terminology is wrong)
The problem I am having is that if I submit the form using the first button, then try again using the second button, it trys to run the first action again on the second submit.
Here's my code which will hopefully make things clearer...
<form id="myForm" action="add.php">
<input type="submit" id="myfunction" />
<input type="submit" id="add" />
<input type="text" name="myvalue" />
</form>
and my validate code...
$("#myForm input[type=submit]").click(function(e) {
if (e.target.id == 'myfunction') {
$("#myForm").validate({
submitHandler: function(form) {
$.post('myfunctionpage.php', $("#myForm").serialize(), function(data) { });
}
});
} else if (e.target.id == 'add') {
$("#myForm").validate({
rules: {
name: {
required: true,
}
}
});
}
});
Why don't you seaprate the code into two segments?
$("#myfunction").click(function(e) {
$("#myForm").validate({
submitHandler: function(form) {
$.post('myfunctionpage.php', $("#myForm").serialize(), function(data) { });
}
});
}
$("#add").click(function(e) {
$("#myForm").validate({
rules: {
name: {
required: true
}
}
});
}
You need to stop the form submission in the $.post case. Try returning false from the click event handler, that should stop the event from bubbling to the form and causing it to submit.
Personally I hook into the submit
event on the form element instead of click events on the buttons. The reason is that many users submit forms by placing the cursor in a text box and then pressing enter. No click event ever occurs and your code is bypassed...
also, its been a while since i used the validate plugin, but i think you're using it wrong calling validate() after a form has been submitted. check the docs for proper use.
Just in case someone is looking for that. Simple after the first submit use $("#myForm").validate().destroy(); in order to clear "form data".