Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect which submit button was clicked

Tags:

jquery

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.

like image 622
Rob Wilkerson Avatar asked Oct 06 '11 11:10

Rob Wilkerson


People also ask

How check submit button is clicked in PHP?

Use isset() method in PHP to test the form is submitted successfully or not. In the code, use isset() function to check $_POST['submit'] method. Remember in place of submit define the name of submit button. After clicking on submit button this action will work as POST method.

What happens when submit button is clicked?

5. Most HTML forms have a submit button at the bottom of the form. Once all of the fields in the form have been filled in, the user clicks on the submit button to record the form data. The standard behaviour is to gather all of the data that were entered into the form and send it to another program to be processed.


1 Answers

Maybe something like this?

http://jsfiddle.net/4wnyY/3/

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.

like image 192
Przemek Avatar answered Oct 08 '22 14:10

Przemek