Reputation: 41236
I know this question sounds a lot like a bunch of others that are out there, but I swear I can't find the right solution anywhere. I have a legacy form that has multiple submit buttons. If one is clicked, I need to do a bit of client-side validation and potentially stop the submit. If the other is clicked, I don't need to do this validation.
What I'm finding is that if I create a .submit()
handler, I can't seem to access which button was actually clicked. On the other hand, if I capture the .click()
event of the button I need to worry about, then I can't prevent the form from submitting via .preventDefault()
(or .stopImmediatePropagation()
).
Here's the most recent iteration of the code that attempts to use the buttons .click()
handler:
$('#nextButton').click( function( e ) {
e.preventDefault(); // The form submits anyway (which kind of makes sense)
// return false also doesn't prevent the submission
// If any session question is unanswered, abort
/* $('#registrants input:text[id$="Answer"]').each( function( i, input ) {
if( $.trim( $(input).val() ) == '' ) {
submit = false;
}
});*/
});
What am I missing here? There has to be a way to do this and it seems like it should be fairly simple, but I'll be damned if I've had any luck at all.
Thanks.
Upvotes: 10
Views: 21101
Reputation: 85
@Przemek has the right answer and approach for this.
I would only add to insure you put your function inside the $(document).ready(function(){}
if you are doing a form submission.
Works across all browsers. See below for the solution that worked for me based on Przemek's example:
//Used to hold the button name of what was clicked
var which;
$(document).ready(function () {
$("button").click(function () {
which = $(this).attr("id");
//alert("Button Clicked Name");
});
$('#searchForm').submit(function (evt) {
if (btnName = "btnSave") {
// do something for the Save option
} else {
// do something different for the Submit or Save and Close option
}
}
}
Upvotes: 0
Reputation: 6700
Maybe something like this?
var which;
$("input").click(function () {
which = $(this).attr("id");
});
$("#form").submit(function () {
if (which == "button2") {
return false; // if "button2" submit clicked - prevent submission
}
});
The main issue with this code would be browser compatibility - i don't know if all browsers work the same, if the click event will be caught before the submit one. I remember that it was different on one version of IE, maybe 7. But it's fixable.
Upvotes: 9
Reputation: 1290
Maybe this helps: http://geekswithblogs.net/renso/archive/2009/09/09/intercept-a-form-submit-with-jquery-and-prevent-or-allow.aspx
Basically what it says is to check the button ID in the form submit() handler.
Upvotes: 3