Note that there are some explanatory texts on larger screens.

plurals
  1. PODetermining which submit button was clicked from jQuery/JavaScript
    text
    copied!<p>I'm ajaxifying some forms from a PHP application I didn't write. To do this, I came up with this clever solution:</p> <pre><code>jQuery("form").submit(function(event) { // get some values from elements on the page: var the_form = jQuery(this); var data = the_form.serialize(); var url = the_form.attr( 'action' ); var button = event.originalEvent.explicitOriginalTarget; data = data + "&amp;" + button.name + "=" + button.value; // Send the data using post and put the results in a div jQuery.post( url, data, function() { //Do something crazy }); // stop form from submitting normally if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } }); </code></pre> <p>Which works perfectly. I went away rejoicing. The problem is, I inadvertently used a Mozilla/Gecko only property to determine which button was clicked. (<code>event.originalEvent.explicitOriginalTarget</code>) Which means this only works in Firefox. :-( </p> <p>All of this is necessary because the web app I'm augmenting relies on the button name/value being in the post data to process the form correctly. So, my question in simple terms would be:</p> <p><strong>What is the best, cross-browser way to determine which button was clicked in jQuery's submit event?</strong></p> <p><strong>Edit:</strong> And here is my solution.</p> <pre><code>jQuery("some selector that targets your form").find(":submit").click(function(event) { // get some values from elements on the page: var the_form = jQuery(this).parents("form"); var data = the_form.serialize(); var url = the_form.attr( 'action' ); var button = event.target; data = data + "&amp;" + button.name + "=" + button.value; // Send the data using post and put the results in a div jQuery.post( url, data, function() { //Do something crazy }); // stop form from submitting normally if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload