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

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

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

提交回复
热议问题