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

后端 未结 26 1633
旧巷少年郎
旧巷少年郎 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: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:

    DUMB CSS:

    input {display:block}
    

提交回复
热议问题