Damovisa
Damovisa

Reputation: 19423

How can I find the button that was clicked from the form submit event in jquery?

I have a function that I'm using to prevent multiple postbacks of a form:

var submitted = false;
$(function() {
    $('form').bind('submit', function(e) {
        if (!submitted && CanSubmit(e)) {
            submitted = true;
            return true;
        } else {
            return false;
        }
    });
});

In the CanSubmit method, I need to interrogate the button that was clicked to determine whether I should allow the submit or not.

Note that I can't bind to specific click events - see this previous question for more details.

In Firefox, I can use e.originalEvent.explicitOriginalTarget, but this is apparently not available in IE.

How can I get this value from the e parameter in a cross-browser way?

Upvotes: 5

Views: 487

Answers (4)

Peter Ajtai
Peter Ajtai

Reputation: 57685

Why don't you unbind the submit function when you do a submit? This will guarantees only one submission:

$(function() {
    $('form').bind('submit', function(event) {
          // regular submit form stuff here
        ...
          // and unbind it
        $('this').unbind(event);       
    });
});

Checkout .unbind() under, "Using the event object"

Or, as Matt Ball pointed out in the comments, you can use .one(), which is equivalent to the above.

$(function() {
    $('form').one('submit', function(event) {           // <== Only executed once
          // regular submit form stuff here
        ...
    });
});

If you have the $.post() or $.get() submission of the form bound to multiple events / elements, then you simply have to make sure to unbind the handler that ends up being used from within itself using the event object, and then unbind all the other handlers too, and vice versa for each of these other handlers. You can unbind the other handlers using one of about four methods to unbind event handlers.

Upvotes: 2

Randall Kwiatkowski
Randall Kwiatkowski

Reputation: 895

Why not use the .one function, guarantees it fires only once.

$(function() {
    $('form').one('submit', function(event) {
      // regular submit form stuff here     
    });
});

Upvotes: 0

Tgr
Tgr

Reputation: 28160

Actually you could just replace $('form').bind('submit' with $(':submit').bind('click' and your code would work just as well (and you could use this to see what was clicked).

Upvotes: 2

Cristian Sanchez
Cristian Sanchez

Reputation: 32117

Use e.target - jQuery normalizes it for cross browser consistency.

The closest thing I could find for explicitOriginalTarget was document.activeElement (for IE) - it is the element that had focus during the event. There is no equivalent for webkit based browsers. So no, there is no real cross browser way to do this with only the event object.

Upvotes: 2

Related Questions