我有一个.submit()事件设置表单提交。我在页面上也有多个表单,但对于这个示例,这里只有一个表单。我想知道哪个提交按钮在没有应用.click()事件的情况下被单击。

下面是设置:

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

jsfiddle的实例

除了在每个按钮上应用.click()事件外,有没有办法确定哪个提交按钮被单击了?


当前回答

区分哪个<button>或<input type="button"…>是通过检查他们的'id'

$("button").click(function() {
  var id = $(this).attr('id');
  ... 
});

其他回答

这个方法对我很管用

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

}

假设我有这些“提交”按钮:

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

这个"submit"事件处理程序:

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

两种表达都可以。如果我点击第一个按钮,“x1”和“x2”都返回更新记录。

这为我工作,以获得活动按钮

            var val = document.activeElement.textContent;

试试这个:

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

对我来说,最好的解决方案是:

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

});