我有一个.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()事件外,有没有办法确定哪个提交按钮被单击了?


当前回答

您可以在提交表单时获得事件对象。从中获取submitter对象。如下:

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

如果希望将该表单发送到后端,可以通过new FormData()创建一个新表单元素,并设置按下按钮的键-值对,然后在后端访问它。就像这样

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

我基本上试图有一个表单,用户可以批准或不批准/拒绝一个产品在一个任务中的进一步处理。 我的HTML表单是这样的

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

如果你有任何疑问请告诉我。

其他回答

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

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

});

这是我使用的解决方案,效果非常好:

// 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(); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <form id="form1" name="form1" action="" method="post"> <input type="text" name="text1" /> <input type="submit" id="button1" value="Submit1" name="button1" /> <button type="submit" id="button2" name="button2"> Submit2 </button> <input type="submit" id="button3" value="Submit3" name="button3" /> </form>

你可以创建input type="hidden"作为按钮id信息的holder。

<input type="hidden" name="button" id="button">
<input type="submit" onClick="document.form_name.button.value = 1;" value="Do something" name="do_something">

在这种情况下,表单在提交时传递值“1”(按钮的id)。如果onClick发生在提交(?)之前,这是有效的,我不确定它是否总是正确的。

哇……很高兴看到这么多解。但是在SubmitEvent接口上有一个原生的Javascript属性提交器。https://developer.mozilla.org/en-US/docs/Web/API/SubmitEvent/submitter

原生Javascript

var btnClicked = event.submitter;

JQuery版本

var btnClicked = event.originalEvent.submitter;

试试这个:

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