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

后端 未结 26 1359
旧巷少年郎
旧巷少年郎 2020-11-22 16:01

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 submi

相关标签:
26条回答
  • 2020-11-22 16:40

    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;
    
    0 讨论(0)
  • 2020-11-22 16:40

    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.

    0 讨论(0)
  • 2020-11-22 16:41

    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);
          });
        });
    
    0 讨论(0)
  • 2020-11-22 16:41

    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');
      ... 
    });
    
    0 讨论(0)
  • 2020-11-22 16:41

    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}
    
    0 讨论(0)
  • 2020-11-22 16:42

    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

    0 讨论(0)
提交回复
热议问题