252

I have a .submit() event set up for form submission. I also have multiple forms on the page, but just one here for this example. I'd like to know which submit button was clicked without applying a .click() event to each one.

Here's the setup:

<html>
<head>
  <title>jQuery research: forms</title>
  <script type='text/javascript' src='../jquery-1.5.2.min.js'></script>
  <script type='text/javascript' language='javascript'>
      $(document).ready(function(){
          $('form[name="testform"]').submit( function(event){ process_form_submission(event); } );
      });
      function process_form_submission( event ) {
          event.preventDefault();
          //var target = $(event.target);
          var me = event.currentTarget;
          var data = me.data.value;
          var which_button = '?';       // <-- this is what I want to know
          alert( 'data: ' + data + ', button: ' + which_button );
      }
  </script>
</head>
<body>
<h2>Here's my form:</h2>
<form action='nothing' method='post' name='testform'>
  <input type='hidden' name='data' value='blahdatayadda' />
  <input type='submit' name='name1' value='value1' />
  <input type='submit' name='name2' value='value2' />
</form>
</body>
</html>

Live example on jsfiddle

Besides applying a .click() event on each button, is there a way to determine which submit button was clicked?

Gupta
  • 8,882
  • 4
  • 49
  • 59
hawkexp
  • 2,623
  • 2
  • 15
  • 4
  • 3
    The irony being of course that this information is trivial to determine server-side. – Neil Apr 19 '11 at 19:52
  • 7
    @Neil Not if you are submitting the form via $.ajax() and a serializeArray() on the form. – Aaron Apr 15 '13 at 00:18
  • possible duplicate of [How can I get the button that caused the submit from the form submit event?](http://stackoverflow.com/questions/2066162/how-can-i-get-the-button-that-caused-the-submit-from-the-form-submit-event) – Bergi Jun 10 '13 at 18:22
  • 1
    How about putting a listener on the submit buttons and submit the form manually. – JMRC Sep 17 '18 at 22:07
  • 1
    How about looking at the serialized version of the form data and match upon button's `name`? – Augustin Riedinger Sep 02 '19 at 15:29

32 Answers32

250

I asked this same question: How can I get the button that caused the submit from the form submit event?

I ended up coming up with this solution and it worked pretty well:

$(document).ready(function() {
    $("form").submit(function() { 
        var val = $("input[type=submit][clicked=true]").val();
        // DO WORK
    });
    $("form input[type=submit]").click(function() {
        $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
        $(this).attr("clicked", "true");
    });
});

In your case with multiple forms you may need to tweak this a bit but it should still apply

Community
  • 1
  • 1
hunter
  • 62,308
  • 19
  • 113
  • 113
  • 11
    +1 Nice solution. You might want to add a statement that resets the clicked attribute to false across the buttons in case the form submit is handled in an ajax way and you want to avoid getting previsouly clicked button again. – Chandu Apr 19 '11 at 19:45
  • 1
    Oh, I see. You're adding your own "clicked" attribute. I was looking all over for a "clicked" boolean and couldn't find one anywhere. I never thought of making one myself. Good idea! – hawkexp Apr 19 '11 at 20:33
  • Do you know which version of jQuery started supporting this? It doesn't seem to work on 1.4.4 which the app I'm working on is unfortunately stuck on... – Alex K Jun 04 '12 at 13:07
  • Any decent version will do. If your version doesn't work, either replace it or ruuuuun! – Fabio Milheiro Jan 19 '14 at 10:50
  • 11
    Be aware that this only works with input elements, not button elements. – Bob.at.Indigo.Health Jun 14 '15 at 23:11
  • In reply to @nfriend21 old comment, this code works fine in Chrome Version 44.0.2403.89 (64-bit). – PanPipes Jul 29 '15 at 16:39
  • The only thing I would add is the form context in the submit handler where you check for the clicked button `$("input[type=submit][clicked=true]", this).val()` should do, and would allow this to work on any of several forms on page! – Trey Oct 27 '15 at 14:27
  • 1
    This is unnecessary in Chrome with button elements. I simply handle the on submit event, construct a FormData object from the form, and it always includes the value of the button that was clicked. FireFox does NOT exhibit this behavior, and instead doesn't send the button value at all. Chrome seems to be doing something like the above solution automatically, remembering which button was clicked and including it in the form data automatically. Of course, this lack of standard behavior (plaguing everything in JavaScript anyway, so I'm not surprised), makes the feature useless. – Triynko Nov 30 '15 at 06:20
  • A problem might arise if any previous handler called on submit event resets the attribute for some reason. Processing all registered handlers may be a complex task involving a lot of foreign code. Nevertheless, this solution is not thread safe and even the user interaction could couse removal of the attribute. The only good solution is to pass the event originator along with the event. You might need to register a handler for every submit button like $('form input[type=submit], form button[type=submit]'.on('click', function(event){handler(event,this);}) passing the submit object. – Kyselejsyreček Feb 16 '17 at 13:31
  • 1
    Also, consider adding the selector "button[type=submit]" (separated by comma) since submit elements don't have to be input tags. – Kyselejsyreček Feb 16 '17 at 13:32
  • 1
    Then is there a way to make it work with button elements rather than `input type="button"...`? – Blaise Aug 16 '17 at 14:42
  • @Blaise Try `$("form button[type=submit]")` – hunter Aug 28 '17 at 17:03
  • Wouldn't it be better to use a data attribute like `data-clicked` rather than a normal attribute which may have meaning in future versions of the browser? – Flimm May 06 '20 at 09:32
  • @Triynko Actually, I can't get the button value from FormData in either Chrome or Firefox. – Flimm May 06 '20 at 10:52
97

I found that this worked.

$(document).ready(function() {
    $( "form" ).submit(function () {
        // Get the submit button element
        var btn = $(this).find("input[type=submit]:focus" );
    });
}
Timo Tijhof
  • 10,032
  • 6
  • 34
  • 48
Stan
  • 1,099
  • 7
  • 7
  • 16
    this solution works well on Chrome, but can't work on Safari, it'll return undefined, not the button object – Mr. Sun Lin May 09 '14 at 14:30
  • 1
    @Krinkle I coded it like that to show the most generic way possible. I think devs are smart enough to optimize it to their tastes. – Stan Jul 25 '14 at 12:13
  • 2
    Cleaner than the other solutions. Still haven't found a solution that works when pressing enter though – andrewtweber Oct 20 '14 at 21:08
  • This answer will not work always. Actually you need the clicked button, not the focused (as the focus action is not a click action). The selected answer (of hunter) is the correct one. – Vasil Popov Dec 04 '14 at 16:07
  • I have a click event on submit buttons and submit events on their forms... the latter triggers the former. I used this to figure out the source of the event. In some browsers clicking the button you'll get the button as focused, in others you'll get nothing. In all browsers I tested, hitting enter while on an input keeps the input focused. – notacouch Mar 11 '15 at 19:51
  • I used the: *$(this).find(":button:focus")* instead. That fetches any of the buttons clicked on the form, instead just the submit buttons. Also, the input[type=submit] wouldn't fetch the * – userfuser Oct 12 '16 at 19:46
75

This works for me:

$("form").submit(function() {
   // Print the value of the button that was clicked
   console.log($(document.activeElement).val());
}
seddonym
  • 16,304
  • 6
  • 66
  • 71
55

When the form is submitted:

  • document.activeElement will give you the submit button that was clicked.

  • document.activeElement.getAttribute('value') will give you that button's value.

Note that if the form is submitted by hitting the Enter key, then document.activeElement will be whichever form input that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."

Nick F
  • 9,781
  • 7
  • 75
  • 90
  • 4
    Note that this doesn't appear to work as expected on Safari. :( – rinogo Jun 09 '17 at 23:14
  • I do not know how about Safari but on Chrome worked good :) Thanks! – Ingus Dec 29 '17 at 09:16
  • Works in Chrome 63 and IE11 – Sir Crispalot Jan 17 '18 at 13:20
  • I had jquery unobtrusive validation running, and that intercepts before this and sets the invalid input as activeElement instead of the button. – Peheje Sep 28 '18 at 09:14
  • This doesn't work with keyboard submission. E.g. if you're focussed on an input and press Enter to submit the form. – Daan Sep 25 '20 at 09:11
  • 1
    Good point @Daan: if you submit the form by hitting Enter there might not _be_ a "button that was clicked." `document.activeElement` still _works_ though: in this case it gives you the input from which the form was submitted instead of a button. I've updated the answer to make this clear. Thanks. – Nick F Sep 27 '20 at 18:44
47

There is a native property, submitter, on the SubmitEvent interface.

Standard Web API:

var btnClicked = event.submitter;

jQuery:

var btnClicked = event.originalEvent.submitter;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
KAR
  • 758
  • 5
  • 8
32

Here's the approach that seems cleaner for my purposes.

First, for any and all forms:

$('form').click(function(event) {
  $(this).data('clicked',$(event.target))
});

When this click event is fired for a form, it simply records the originating target (available in the event object) to be accessed later. This is a pretty broad stroke, as it will fire for any click anywhere on the form. Optimization comments are welcome, but I suspect it will never cause noticeable issues.

Then, in $('form').submit(), you can inquire what was last clicked, with something like

if ($(this).data('clicked').is('[name=no_ajax]')) xhr.abort();
David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
Jonathan Camenisch
  • 3,472
  • 1
  • 20
  • 9
  • What if this is an form submit event instead of click? – Tony Nov 05 '12 at 10:25
  • 1
    @Tony, sorry I didn't see your question sooner. This answer is entirely in regards to form submits. Submit buttons get clicked too, and thus they fire the click event. – Jonathan Camenisch Dec 17 '12 at 22:53
  • 2
    Upvoting this answer over [hunter's answer](http://stackoverflow.com/a/5721762/141881) since the form's submit events are fired before any child element click events. This causes difficulties when your form's submit event is cancelled with `return false`, whereas this method works correctly since the click is bound to the form instead of its children. – pospi Jan 27 '13 at 07:46
  • 7
    This fails to properly handle the case where the form is submitted by means other than a click (e.g., pressing Enter). When the form is submitted via other means, it is the first submit button that triggered the submit event, not the one last clicked. – quietmint Feb 28 '13 at 15:48
  • There is a semicolon missing after `... $(event.target))` but can't edit because edits must be > 6 chars – Hafenkranich Jun 02 '15 at 14:26
  • This is not a thread safe approach. See my comment below the accepted answer. – Kyselejsyreček Feb 16 '17 at 13:35
13

Wow, some solutions can get complicated! If you don't mind using a simple global, just take advantage of the fact that the input button click event fires first. One could further filter the $('input') selector for one of many forms by using $('#myForm input').

    $(document).ready(function(){
      var clkBtn = "";
      $('input[type="submit"]').click(function(evt) {
        clkBtn = evt.target.id;
      });

      $("#myForm").submit(function(evt) {
        var btnID = clkBtn;
        alert("form submitted; button id=" + btnID);
      });
    });
lawnbowler
  • 130
  • 1
  • 6
13

I have found the best solution is

$(document.activeElement).attr('id')

This not only works on inputs, but it also works on button tags. Also it gets the id of the button.

Thomas Williams
  • 1,528
  • 1
  • 18
  • 37
  • Damn I have to see if my page works on Safari now doh. Why does Safari always have to be so difficult. Thanks for that. Going to check when I get home – Thomas Williams Feb 16 '17 at 15:27
  • https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement#Browser_compatibility – Oliver Hader Mar 23 '18 at 08:34
  • This isn't working for me in Safari. Click listener on a Button in the body calls .submit on a form. Inside the submit handler `$(document.activeElement).attr('id')` returns `undefined` – dyodji Apr 30 '20 at 21:27
  • This doesn't work with keyboard submission. E.g. if you're focussed on an input and press Enter to submit the form. – Daan Sep 25 '20 at 09:11
7

Another possible solution is to add a hidden field in your form:

<input type="hidden" id="btaction"/>

Then in the ready function add functions to record what key was pressed:

$('form#myForm #btnSubmit').click(function() {
    $('form#myForm #btaction').val(0);
});

$('form#myForm #btnSubmitAndSend').click(function() {
    $('form#myForm #btaction').val(1);
});

$('form#myForm #btnDelete').click(function() {
    $('form#myForm #btaction').val(2);
});

Now in the form submition handler read the hidden variable and decide based on it:

var act = $('form#myForm #btaction').val();
wmac
  • 1,023
  • 1
  • 16
  • 34
6

Building on what Stan and yann-h did but this one defaults to the first button. The beauty of this overall approach is that it picks up both the click and the enter key (even if the focus was not on the button. If you need to allow enter in the form, then just respond to this when a button is focused (i.e. Stan's answer). In my case, I wanted to allow enter to submit the form even if the user's current focus was on the text box.

I was also using a 'name' attribute rather than 'id' but this is the same approach.

var pressedButtonName =
     typeof $(":input[type=submit]:focus")[0] === "undefined" ?
     $(":input[type=submit]:first")[0].name :
     $(":input[type=submit]:focus")[0].name;
andrewmo
  • 1,922
  • 1
  • 17
  • 20
5

This one worked for me

$('#Form').submit(function(){
var btn= $(this).find("input[type=submit]:focus").val();
alert('you have clicked '+ btn);

}
Saheb Mondal
  • 163
  • 1
  • 7
5

Here is my solution:

   $('#form').submit(function(e){   
        console.log($('#'+e.originalEvent.submitter.id));
        e.preventDefault();
    });
Roldan
  • 225
  • 2
  • 14
  • It will only work if an id is assigned to the button, however, since `event.originalEvent.submitter` is the button, it is possible to read other uniquely assigned attributes from it. – AaA May 29 '21 at 10:42
5

You can simply get the event object when you submit the form. From that, get the submitter object. As below:

$(".review-form").submit(function (e) {
        e.preventDefault(); // avoid to execute the actual submit of the form.

        let submitter_btn = $(e.originalEvent.submitter);
        
        console.log(submitter_btn.attr("name"));
}

In case you want to send this form to the backend, you can create a new form element by new FormData() and set the key-value pair for which button was pressed, then access it in the backend. Something like this -

$(".review-form").submit(function (e) {
        e.preventDefault(); // avoid to execute the actual submit of the form.

        let form = $(this);
        let newForm = new FormData($(form)[0]);
        let submitter_btn = $(e.originalEvent.submitter);
        
        console.log(submitter_btn.attr("name"));

        if ((submitter_btn.attr("name") == "approve_btn") || 
            (submitter_btn.attr("name") == "reject_btn")){
            newForm.set("action_for", submitter_btn.attr("name"));
        } else {
            console.log("there is some error!");
            return;
        }
}

I was basically trying to have a form where user can either approve or disapprove/ reject a product for further processes in a task. My HTML form is something like this -

<form method="POST" action="{% url 'tasks:review-task' taskid=product.task_id.id %}"
    class="review-form">
    {% csrf_token %}
    <input type="hidden" name="product_id" value="{{product.product_id}}" />
    <input type="hidden" name="task_id" value="{{product.task_id_id}}" />
    <button type="submit" name="approve_btn" class="btn btn-link" id="approve-btn">
        <i class="fa fa-check" style="color: rgb(63, 245, 63);"></i>
    </button>
    <button type="submit" name="reject_btn" class="btn btn-link" id="reject-btn">
            <i class="fa fa-times" style="color: red;"></i>
    </button>
</form>

Let me know if you have any doubts.

4

As I can't comment on the accepted answer, I bring here a modified version that should take into account elements that are outside the form (ie: attached to the form using the form attribute). This is for modern browser: http://caniuse.com/#feat=form-attribute . The closest('form') is used as a fallback for unsupported form attribute

$(document).on('click', '[type=submit]', function() {
    var form = $(this).prop('form') || $(this).closest('form')[0];
    $(form.elements).filter('[type=submit]').removeAttr('clicked')
    $(this).attr('clicked', true);
});

$('form').on('submit', function() {
    var submitter = $(this.elements).filter('[clicked]');
})
user3074069
  • 144
  • 11
  • This really should be the selected answer. I would only add that the rule should be `"button,[type=submit]"` – Wil Jul 04 '18 at 23:32
  • @Wil but not all buttons are submit buttons, it depends on their type. – ptyskju Dec 31 '19 at 11:06
  • Yes, but in the absence of a ], every UA I have ever used has treated a – Wil Jan 06 '20 at 23:23
4

If what you mean by not adding a .click event is that you don't want to have separate handlers for those events, you could handle all clicks (submits) in one function:

$(document).ready(function(){
  $('input[type="submit"]').click( function(event){ process_form_submission(event); } );
});

function process_form_submission( event ) {
  event.preventDefault();
  //var target = $(event.target);
  var input = $(event.currentTarget);
  var which_button = event.currentTarget.value;
  var data = input.parents("form")[0].data.value;
//  var which_button = '?';       // <-- this is what I want to know
  alert( 'data: ' + data + ', button: ' + which_button );
}
jcane86
  • 681
  • 4
  • 17
  • not a bad idea. Would this works for any number of forms on the page? – hawkexp Apr 19 '11 at 20:44
  • @hawk yep, it should. I don't know if this is desired behavior, but your code doesn't actually submit the form, so mine doesn't either. If you do want to submit it just remove the `event.preventDefault` or do something like `input.parents("form")[0].submit()`. – jcane86 Apr 19 '11 at 20:55
  • And if you submit without a click (return key?) it will be a total mess.. – FrancescoMM Oct 12 '17 at 13:54
4

Try this:

$(document).ready(function(){
    
    $('form[name="testform"]').submit( function(event){
      
        // This is the ID of the clicked button
        var clicked_button_id = event.originalEvent.submitter.id; 
        
    });
});
Greeso
  • 7,544
  • 9
  • 51
  • 77
  • This is exactly same as another answer from a year earlier. It will only work if an id is assigned to the button, however, since `event.originalEvent.submitter` is the button, it is possible to read other uniquely assigned attributes from it. – AaA May 29 '21 at 10:39
3
$("form input[type=submit]").click(function() {
    $("<input />")
        .attr('type', 'hidden')
        .attr('name', $(this).attr('name'))
        .attr('value', $(this).attr('value'))
    .appendTo(this)
});

add hidden field

anydasa
  • 2,616
  • 1
  • 15
  • 13
  • Does not work in Firefox 30 / Windows 7. Note: a hidden field is required now in firefox, as it might not send the clicked submit value if sent with jquery's: this.submit() in an on-submit event. I am just a little bit concerned that $(this).attr('name') might not be working across all browsers. – user1610743 Jul 02 '14 at 10:18
  • I Have Firefox 30 / Windows 7. I have everything working perfectly. – anydasa Jul 05 '14 at 03:37
  • Remember to include `button[type=submit]` and `input[type=image]`. – rybo111 Nov 24 '15 at 09:57
3

For me, the best solutions was this:

$(form).submit(function(e){

   // Get the button that was clicked       
   var submit = $(this.id).context.activeElement;

   // You can get its name like this
   alert(submit.name)

   // You can get its attributes like this too
   alert($(submit).attr('class'))

});
Jeramiah Harland
  • 854
  • 7
  • 15
3

Working with this excellent answer, you can check the active element (the button), append a hidden input to the form, and optionally remove it at the end of the submit handler.

$('form.form-js').submit(function(event){
    var frm = $(this);
    var btn = $(document.activeElement);
    if(
        btn.length &&
        frm.has(btn) &&
        btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&
        btn.is('[name]')
    ){
        frm.append('<input type="hidden" id="form-js-temp" name="' + btn.attr('name') + '" value="' + btn.val() + '">');
    }

    // Handle the form submit here

    $('#form-js-temp').remove();
});

Side note: I personally add the class form-js on all forms that are submitted via JavaScript.

Community
  • 1
  • 1
rybo111
  • 12,240
  • 4
  • 61
  • 70
2

Similar to Stan answer but :

  • if you have more than one button, you have to get only the first button => [0]
  • if the form can be submitted with the enter key, you have to manage a default => myDefaultButtonId

$(document).on('submit', function(event) {
    event.preventDefault();
    var pressedButtonId = 
         typeof $(":input[type=submit]:focus")[0] === "undefined" ? 
         "myDefaultButtonId" :
         $(":input[type=submit]:focus")[0].id;
    ...
 }
yann-h
  • 521
  • 4
  • 7
2

This is the solution used by me and work very well:

// prevent enter key on some elements to prevent to submit the form
function stopRKey(evt) {
  evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  var alloved_enter_on_type = ['textarea'];
  if ((evt.keyCode == 13) && ((node.id == "") || ($.inArray(node.type, alloved_enter_on_type) < 0))) {
    return false;
  }
}

$(document).ready(function() {
  document.onkeypress = stopRKey;
  // catch the id of submit button and store-it to the form
  $("form").each(function() {
    var that = $(this);

    // define context and reference
    /* for each of the submit-inputs - in each of the forms on
    the page - assign click and keypress event */
    $("input:submit,button", that).bind("click keypress", function(e) {
      // store the id of the submit-input on it's enclosing form
      that.data("callerid", this.id);
    });
  });

  $("#form1").submit(function(e) {
    var origin_id = $(e.target).data("callerid");
    alert(origin_id);
    e.preventDefault();

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="form1" name="form1" action="" method="post">
  <input type="text" name="text1" />
  <input type="submit" id="button1" value="Submit1" name="button1" />
  <button type="submit" id="button2" name="button2">
    Submit2
  </button>
  <input type="submit" id="button3" value="Submit3" name="button3" />
</form>
vasilenicusor
  • 2,023
  • 1
  • 21
  • 37
2

This works for me to get the active button

            var val = document.activeElement.textContent;
1

It helped me https://stackoverflow.com/a/17805011/1029257

Form submited only after submit button was clicked.

var theBtn = $(':focus');
if(theBtn.is(':submit'))
{
  // ....
  return true;
}

return false;
Community
  • 1
  • 1
w4kskl
  • 141
  • 1
  • 6
1

I was able to use jQuery originalEvent.submitter on Chrome with an ASP.Net Core web app:

My .cshtml form:

<div class="form-group" id="buttons_grp">
    <button type="submit" name="submitButton" value="Approve" class="btn btn-success">Approve</button>
    <button type="submit" name="submitButton" value="Reject" class="btn btn-danger">Reject</button>
    <button type="submit" name="submitButton" value="Save" class="btn btn-primary">Save</button>
    ...

The jQuery submit handler:

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
    $(document).ready(function() {
    ...
    // Ensure that we log an explanatory comment if "Reject"
    $('#update_task_form').on('submit', function (e) {
        let text = e.originalEvent.submitter.textContent;
        if (text == "Reject") {
           // Do stuff...
        }
    });
    ...

The jQuery Microsoft bundled with my ASP.Net Core environment is v3.3.1.

paulsm4
  • 114,292
  • 17
  • 138
  • 190
1

Let's say I have these "submit" buttons:

<button type="submit" name="submitButton" id="update" value="UpdateRecord" class="btn btn-primary">Update Record</button>
<button type="submit" name="submitButton" id="review_info" value="ReviewInfo" class="btn btn-warning sme_only">Review Info</button>
<button type="submit" name="submitButton" id="need_more_info" value="NeedMoreInfo" class="btn btn-warning sme_only">Need More Info</button>

And this "submit" event handler:

 $('#my_form').on('submit', function (e) {
     let x1 = $(this).find("input[type=submit]:focus");
     let x2 = e.originalEvent.submitter.textContent;

Either expression works. If I click the first button, both "x1" and "x2" return Update Record.

paulsm4
  • 114,292
  • 17
  • 138
  • 190
0

I also made a solution, and it works quite well:
It uses jQuery and CSS


First, I made a quick CSS class, this can be embedded or in a seperate file.

<style type='text/css'>
    .Clicked {
        /*No Attributes*/
    }
</style>


Next, On the click event of a button within the form,add the CSS class to the button. If the button already has the CSS class, remove it. (We don't want two CSS classes [Just in case]).

    // Adds a CSS Class to the Button That Has Been Clicked.
    $("form :input[type='submit']").click(function () 
    {
        if ($(this).hasClass("Clicked"))
        {
            $(this).removeClass("Clicked");
        }
        $(this).addClass("Clicked");
    });


Now, test the button to see it has the CSS class, if the tested button doesn't have the CSS, then the other button will.

    // On Form Submit
    $("form").submit(function ()
    {
        // Test Which Button Has the Class
        if ($("input[name='name1']").hasClass("Clicked"))
        {
            // Button 'name1' has been clicked.
        }
        else
        {
           // Button 'name2' has been clicked.
        }
    });

Hope this helps! Cheers!

Jason Cidras
  • 509
  • 5
  • 11
  • Remember to include `button[type=submit]` and `input[type=image]`. – rybo111 Nov 24 '15 at 09:55
  • You should remove references to styling and CSS - they are not relevant here. Also, the lines where you use `hasClass()` and `removeClass()` are redundant, as `addClass()` will not add the same class twice. – rybo111 Nov 27 '15 at 23:19
0

You can create input type="hidden" as holder for a button id information.

<input type="hidden" name="button" id="button">
<input type="submit" onClick="document.form_name.button.value = 1;" value="Do something" name="do_something">

In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.

darekk
  • 71
  • 1
  • 13
0

A simple way to distinguish which <button> or <input type="button"...> is pressed, is by checking their 'id':

$("button").click(function() {
  var id = $(this).attr('id');
  ... 
});
Apostolos
  • 3,115
  • 25
  • 28
0

Here is a sample, that uses this.form to get the correct form the submit is into, and data fields to store the last clicked/focused element. I also wrapped submit code inside a timeout to be sure click events happen before it is executed (some users reported in comments that on Chrome sometimes a click event is fired after a submit).

Works when navigating both with keys and with mouse/fingers without counting on browsers to send a click event on RETURN key (doesn't hurt though), I added an event handler for focus events for buttons and fields.

You might add buttons of type="submit" to the items that save themselves when clicked.

In the demo I set a red border to show the selected item and an alert that shows name and value/label.

Here is the FIDDLE

And here is the (same) code:

Javascript:

$("form").submit(function(e) {
  e.preventDefault();
  // Use this for rare/buggy cases when click event is sent after submit
  setTimeout(function() {

    var $this=$(this);
    var lastFocus = $this.data("lastFocus");
    var $defaultSubmit=null;

    if(lastFocus) $defaultSubmit=$(lastFocus);

    if(!$defaultSubmit || !$defaultSubmit.is("input[type=submit]")) {
      // If for some reason we don't have a submit, find one (the first)
      $defaultSubmit=$(this).find("input[type=submit]").first();
    }

    if($defaultSubmit) {
      var submitName=$defaultSubmit.attr("name");
      var submitLabel=$defaultSubmit.val();

       // Just a demo, set hilite and alert
      doSomethingWith($defaultSubmit);
      setTimeout(function() {alert("Submitted "+submitName+": '"+submitLabel+"'")},1000);
    } else {
      // There were no submit in the form
    }

  }.bind(this),0);

});

$("form input").focus(function() {
  $(this.form).data("lastFocus", this);
});
$("form input").click(function() {
  $(this.form).data("lastFocus", this);
});

// Just a demo, setting hilite
function doSomethingWith($aSelectedEl) {
  $aSelectedEl.css({"border":"4px solid red"});
  setTimeout(function() { $aSelectedEl.removeAttr("style"); },1000);
}

DUMMY HTML:

<form>
<input type="text" name="testtextortexttest" value="Whatever you write, sir."/>
<input type="text" name="moretesttextormoretexttest" value="Whatever you write, again, sir."/>

<input type="submit" name="test1" value="Action 1"/>
<input type="submit" name="test2" value="Action 2"/>
<input type="submit" name="test3" value="Action 3"/>
<input type="submit" name="test4" value="Action 4"/>
<input type="submit" name="test5" value="Action 5"/>
</form>

DUMB CSS:

input {display:block}
FrancescoMM
  • 2,845
  • 1
  • 18
  • 29
0

I write this function that helps me

var PupulateFormData= function (elem) {
var arr = {};
$(elem).find("input[name],select[name],button[name]:focus,input[type='submit']:focus").each(function () {
    arr[$(this).attr("name")] = $(this).val();
});
return arr;
};

and then Use

var data= PupulateFormData($("form"));
BabiBN
  • 91
  • 1
  • 2
0
$('form').submit(function (ev) {
  let clickedButton = ev.originalEvent.explicitOriginalTarget;
});
Alexandre Paulo
  • 2,427
  • 1
  • 14
  • 12
-2

You want to use window.event.srcElement.id like this:

function clickTheButton() {

var Sender = window.event.srcElement;
alert("the item clicked was " + Sender.id)

}

for a button that looks like:

<input type="button" id="myButton" onclick="clickTheButton();" value="Click Me"/>

you will get an alert that reads: "the item clicked was myButton.

In your improved example you can add window.event.srcElement to process_form_submission and you will have a reference to whichever element invoked the process.

Cos Callis
  • 5,051
  • 3
  • 30
  • 57