ChatGPT解决这个技术问题 Extra ChatGPT

jQuery: how to get which button was clicked upon form submission?

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?

The irony being of course that this information is trivial to determine server-side.
@Neil Not if you are submitting the form via $.ajax() and a serializeArray() on the form.
How about putting a listener on the submit buttons and submit the form manually.
How about looking at the serialized version of the form data and match upon button's name?

C
Community

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


+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.
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!
Be aware that this only works with input elements, not button elements.
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.
Also, consider adding the selector "button[type=submit]" (separated by comma) since submit elements don't have to be input tags.
T
Timo Tijhof

I found that this worked.

$(document).ready(function() {
    $( "form" ).submit(function () {
        // Get the submit button element
        var btn = $(this).find("input[type=submit]:focus" );
    });
}

this solution works well on Chrome, but can't work on Safari, it'll return undefined, not the button object
@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.
Cleaner than the other solutions. Still haven't found a solution that works when pressing enter though
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.
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.
s
seddonym

This works for me:

$("form").submit(function() {
   // Print the value of the button that was clicked
   console.log($(document.activeElement).val());
}

This was helpful, to get the id of the activeElement, I did $(document.activeElement).attr('id');
For what it's worth, you don't need to use jQuery to get the id - it's even simpler to use pure Javascript: document.activeElement.id
Note that this doesn't appear to work as expected on Safari. :(
In Safari document.activeElement is not the input. In my case it's a modal div (which contains the form).
This doesn't work with keyboard submission. E.g. if you're focussed on an input and press Enter to submit the form.
N
Nick F

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."


Note that this doesn't appear to work as expected on Safari. :(
I do not know how about Safari but on Chrome worked good :) Thanks!
Works in Chrome 63 and IE11
I had jquery unobtrusive validation running, and that intercepts before this and sets the invalid input as activeElement instead of the button.
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.
D
David Ferenczy Rogožan

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();

What if this is an form submit event instead of click?
@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.
Upvoting this answer over hunter's answer 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.
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.
There is a semicolon missing after ... $(event.target)) but can't edit because edits must be > 6 chars
K
KAR

Wow... nice to see too many solutions here. but there was a native Javascript property submitter on the SubmitEvent interface. https://developer.mozilla.org/en-US/docs/Web/API/SubmitEvent/submitter

Native Javascript

var btnClicked = event.submitter;

JQuery version

var btnClicked = event.originalEvent.submitter;

This is the cleanest solution!
Important to note it's not supported by IE though.
l
lawnbowler

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);
      });
    });

T
Thomas Williams

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.


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
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
This doesn't work with keyboard submission. E.g. if you're focussed on an input and press Enter to submit the form.
w
wmac

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();

a
andrewmo

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;

So if you move focus to the second button with TAB and press RETURN it will default to the first button...
S
Saheb Mondal

This one worked for me

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

}

This deserves medal!
How is this any different than the answer provided by @Stan ?
R
Roldan

Here is my solution:

   $('#form').submit(function(e){   
        console.log($('#'+e.originalEvent.submitter.id));
        e.preventDefault();
    });

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.
j
jcane86

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 );
}

not a bad idea. Would this works for any number of forms on the page?
@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().
And if you submit without a click (return key?) it will be a total mess..
u
user3074069

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]');
})

This really should be the selected answer. I would only add that the rule should be "button,[type=submit]"
@Wil but not all buttons are submit buttons, it depends on their type.
Yes, but in the absence of a ], every UA I have ever used has treated a
K
Karishma Sukhwani

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") {
            newForm.set("action_for", submitter_btn.attr("name"));
        } else if (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.


G
Greeso

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; 
        
    });
});

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.
a
anydasa
$("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


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.
I Have Firefox 30 / Windows 7. I have everything working perfectly.
Remember to include button[type=submit] and input[type=image].
J
Jeramiah Harland

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'))

});

C
Community

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.


y
yann-h

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;
    ...
 }

v
vasilenicusor

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(); }); });


M
Mariana Nagy

This works for me to get the active button

            var val = document.activeElement.textContent;

C
Community

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;

p
paulsm4

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.


p
paulsm4

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.


J
Jason Cidras

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!


Remember to include button[type=submit] and input[type=image].
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.
d
darekk

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.


A
Apostolos

A simple way to distinguish which

F
FrancescoMM

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}

B
BabiBN

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"));