jQuery:如何获取表单提交时单击的按钮?

时间:2021-06-25 21:19: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 submit button was clicked without applying a .click() event to each one.

我有一个.submit()事件设置为提交表单。我在页面上也有多个表单,但是在这里仅举一个例子。我想知道哪个提交按钮没有应用。click()事件对每一个。

Here's the setup:

这是设置:

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

Live example on jsfiddle

生活例子jsfiddle

Besides applying a .click() event on each button, is there a way to determine which submit button was clicked?

除了在每个按钮上应用.click()事件之外,是否有办法确定单击了哪个submit按钮?

23 个解决方案

#1


194  

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

在多表单的情况下,您可能需要稍微调整一下,但它仍然应该适用

#2


73  

I found that this worked.

我发现这很有效。

$(document).ready(function() {
    $( "form" ).submit(function () {
        // Get the submit button element
        var btn = $(this).find("input[type=submit]:focus" );
    });
}

#3


50  

This works for me:

这工作对我来说:

$("form").submit(function() {
   // Print the value of the button that was clicked
   console.log($(document.activeElement).val());
}

#4


32  

When the form is submitted:

提交表格时:

  • document.activeElement will give you the submit button that was clicked.

    文档。activeElement将为您提供单击的submit按钮。

  • document.activeElement.getAttribute('value') will give you that button's value.

    getattribute ('value')将为您提供该按钮的值。

#5


25  

Here's the approach that seems cleaner for my purposes.

这是一种对我来说更简洁的方法。

First, for any and all forms:

首先,对于任何和所有形式:

$('form').click(function(event) {
  $(this).data('clicked',$(event.target))
});

When this click event is fired for a form, it simply records the originating target (available in the event object) to be accessed later. This is a pretty broad stroke, as it will fire for any click anywhere on the form. Optimization comments are welcome, but I suspect it will never cause noticeable issues.

当为窗体触发此单击事件时,它只记录稍后要访问的原始目标(在事件对象中可用)。这是一种非常广泛的操作,因为它会在窗体上的任何地方触发任何单击。优化注释是受欢迎的,但是我怀疑它不会引起明显的问题。

Then, in $('form').submit(), you can inquire what was last clicked, with something like

然后,在$('form').submit()中,您可以查询最后单击的内容,内容如下

if ($(this).data('clicked').is('[name=no_ajax]')) xhr.abort();

#6


10  

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').

哇,有些解决方案会变得很复杂!如果您不介意使用一个简单的全局变量,只需利用输入按钮单击事件首先触发这一事实。通过使用$('#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);
      });
    });

#7


6  

Another possible solution is to add a hidden field in your form:

另一个可能的解决方案是在表单中添加一个隐藏字段:

<input type="hidden" id="btaction"/>

Then in the ready function add functions to record what key was pressed:

然后在就绪函数中添加函数,记录按下的键:

$('form#myForm #btnSubmit').click(function() {
    $('form#myForm #btaction').val(0);
});

$('form#myForm #btnSubmitAndSend').click(function() {
    $('form#myForm #btaction').val(1);
});

$('form#myForm #btnDelete').click(function() {
    $('form#myForm #btaction').val(2);
});

Now in the form submition handler read the hidden variable and decide based on it:

现在在表单submition handler中读取隐藏变量并根据它做出决定:

var act = $('form#myForm #btaction').val();

#8


6  

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.

建立在Stan和yann-h所做的基础上但是这个是默认的第一个按钮。这种整体方法的优点在于,它同时接收单击和enter键(即使焦点不在按钮上)。如果您需要允许输入表单,那么当按钮被关注时(即Stan的答案),您只需对此做出响应。在我的例子中,我希望允许enter提交表单,即使用户当前的焦点是文本框。

I was also using a 'name' attribute rather than 'id' but this is the same approach.

我还使用了“name”属性而不是“id”,但这是相同的方法。

var pressedButtonName =
     typeof $(":input[type=submit]:focus")[0] === "undefined" ?
     $(":input[type=submit]:first")[0].name :
     $(":input[type=submit]:focus")[0].name;

#9


6  

I have found the best solution is

我找到了最好的解决办法

$(document.activeElement).attr('id')

This not only works on inputs, but it also works on button tags. Also it gets the id of the button.

这不仅适用于输入,也适用于按钮标签。它还获取按钮的id。

#10


4  

If what you mean by not adding a .click event is that you don't want to have separate handlers for those events, you could handle all clicks (submits) in one function:

如果您不添加.click事件的意思是您不想为这些事件拥有单独的处理程序,那么您可以在一个函数中处理所有单击(提交):

$(document).ready(function(){
  $('input[type="submit"]').click( function(event){ process_form_submission(event); } );
});

function process_form_submission( event ) {
  event.preventDefault();
  //var target = $(event.target);
  var input = $(event.currentTarget);
  var which_button = event.currentTarget.value;
  var data = input.parents("form")[0].data.value;
//  var which_button = '?';       // <-- this is what I want to know
  alert( 'data: ' + data + ', button: ' + which_button );
}

#11


4  

This one worked for me

这个对我起作用了。

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

}

#12


3  

$("form input[type=submit]").click(function() {
    $("<input />")
        .attr('type', 'hidden')
        .attr('name', $(this).attr('name'))
        .attr('value', $(this).attr('value'))
    .appendTo(this)
});

add hidden field

添加隐藏字段

#13


3  

For me, the best solutions was this:

对我来说,最好的解决办法是:

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

});

#14


3  

Working with this excellent answer, you can check the active element (the button), append a hidden input to the form, and optionally remove it at the end of the submit handler.

使用这个优秀的答案,您可以检查活动元素(按钮),向表单添加隐藏的输入,并可以在提交处理程序的末尾删除它。

$('form.form-js').submit(function(event){
    var frm = $(this);
    var btn = $(document.activeElement);
    if(
        btn.length &&
        frm.has(btn) &&
        btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&
        btn.is('[name]')
    ){
        frm.append('<input type="hidden" id="form-js-temp" name="' + btn.attr('name') + '" value="' + btn.val() + '">');
    }

    // Handle the form submit here

    $('#form-js-temp').remove();
});

Side note: I personally add the class form-js on all forms that are submitted via JavaScript.

附注:我个人在所有通过JavaScript提交的表单上添加了form-js类。

#15


2  

Similar to Stan answer but :

类似于Stan的回答,但是:

  • if you have more than one button, you have to get only the first button => [0]
  • 如果您有多个按钮,您必须只获得第一个按钮=> [0]
  • if the form can be submitted with the enter key, you have to manage a default => myDefaultButtonId
  • 如果可以使用enter键提交表单,则必须管理一个默认的=> myDefaultButtonId

$(document).on('submit', function(event) {
    event.preventDefault();
    var pressedButtonId = 
         typeof $(":input[type=submit]:focus")[0] === "undefined" ? 
         "myDefaultButtonId" :
         $(":input[type=submit]:focus")[0].id;
    ...
 }

#16


2  

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

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

#17


1  

It helped me https://*.com/a/17805011/1029257

它帮助我https://*.com/a/17805011/1029257

Form submited only after submit button was clicked.

只有在提交按钮被点击后才能提交表单。

var theBtn = $(':focus');
if(theBtn.is(':submit'))
{
  // ....
  return true;
}

return false;

#18


1  

As I can't comment on the accepted answer, I bring here a modified version that should take into account elements that are outside the form (ie: attached to the form using the form attribute). This is for modern browser: http://caniuse.com/#feat=form-attribute . The closest('form') is used as a fallback for unsupported form attribute

由于我无法对已接受的答案进行评论,因此我在这里提供了一个修改后的版本,它应该考虑到表单之外的元素(即:使用表单属性附加到表单上)。这是针对现代浏览器的:http://caniuse.com/#feat=form-attribute。最近的(“form”)用作不支持的form属性的回退

$(document).on('click', '[type=submit]', function() {
    var form = $(this).prop('form') || $(this).closest('form')[0];
    $(form.elements).filter('[type=submit]').removeAttr('clicked')
    $(this).attr('clicked', true);
});

$('form').on('submit', function() {
    var submitter = $(this.elements).filter('[clicked]');
})

#19


0  

I also made a solution, and it works quite well:
It uses jQuery and CSS

我还做了一个解决方案,它工作得很好:它使用jQuery和CSS


First, I made a quick CSS class, this can be embedded or in a seperate file.

首先,我创建了一个快速CSS类,它可以被嵌入或者被分离的文件。

<style type='text/css'>
    .Clicked {
        /*No Attributes*/
    }
</style>


Next, On the click event of a button within the form,add the CSS class to the button. If the button already has the CSS class, remove it. (We don't want two CSS classes [Just in case]).

接下来,在表单中单击按钮的事件上,向按钮添加CSS类。如果按钮已经有CSS类,那么删除它。(我们不需要两个CSS类(以防万一))。

    // Adds a CSS Class to the Button That Has Been Clicked.
    $("form :input[type='submit']").click(function () 
    {
        if ($(this).hasClass("Clicked"))
        {
            $(this).removeClass("Clicked");
        }
        $(this).addClass("Clicked");
    });


Now, test the button to see it has the CSS class, if the tested button doesn't have the CSS, then the other button will.

现在,测试这个按钮,看看它有CSS类,如果测试的按钮没有CSS,那么另一个按钮会。

    // On Form Submit
    $("form").submit(function ()
    {
        // Test Which Button Has the Class
        if ($("input[name='name1']").hasClass("Clicked"))
        {
            // Button 'name1' has been clicked.
        }
        else
        {
           // Button 'name2' has been clicked.
        }
    });

Hope this helps! Cheers!

希望这可以帮助!干杯!

#20


0  

You can create input type="hidden" as holder for a button id information.

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

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

In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.

在这种情况下,表单在提交时传递值“1”(您的按钮的id)。如果在submit(?)之前出现onClick,那么它就可以工作,我不确定它是否总是正确的。

#21


0  

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');
  ... 
});

#22


0  

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.

您可以将type="submit"按钮添加到单击时保存的项中。

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:

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:

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:

愚蠢的CSS:

input {display:block}

#23


-1  

You want to use window.event.srcElement.id like this:

您想要使用window.event.srcElement。id是这样的:

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.

您将得到一个警告,该警告如下:“单击的项目是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.

在改进的示例中,可以添加window.event。到process_form_submission的srcElement,您将获得对调用该过程的任何元素的引用。

#1


194  

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

在多表单的情况下,您可能需要稍微调整一下,但它仍然应该适用

#2


73  

I found that this worked.

我发现这很有效。

$(document).ready(function() {
    $( "form" ).submit(function () {
        // Get the submit button element
        var btn = $(this).find("input[type=submit]:focus" );
    });
}

#3


50  

This works for me:

这工作对我来说:

$("form").submit(function() {
   // Print the value of the button that was clicked
   console.log($(document.activeElement).val());
}

#4


32  

When the form is submitted:

提交表格时:

  • document.activeElement will give you the submit button that was clicked.

    文档。activeElement将为您提供单击的submit按钮。

  • document.activeElement.getAttribute('value') will give you that button's value.

    getattribute ('value')将为您提供该按钮的值。

#5


25  

Here's the approach that seems cleaner for my purposes.

这是一种对我来说更简洁的方法。

First, for any and all forms:

首先,对于任何和所有形式:

$('form').click(function(event) {
  $(this).data('clicked',$(event.target))
});

When this click event is fired for a form, it simply records the originating target (available in the event object) to be accessed later. This is a pretty broad stroke, as it will fire for any click anywhere on the form. Optimization comments are welcome, but I suspect it will never cause noticeable issues.

当为窗体触发此单击事件时,它只记录稍后要访问的原始目标(在事件对象中可用)。这是一种非常广泛的操作,因为它会在窗体上的任何地方触发任何单击。优化注释是受欢迎的,但是我怀疑它不会引起明显的问题。

Then, in $('form').submit(), you can inquire what was last clicked, with something like

然后,在$('form').submit()中,您可以查询最后单击的内容,内容如下

if ($(this).data('clicked').is('[name=no_ajax]')) xhr.abort();

#6


10  

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').

哇,有些解决方案会变得很复杂!如果您不介意使用一个简单的全局变量,只需利用输入按钮单击事件首先触发这一事实。通过使用$('#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);
      });
    });

#7


6  

Another possible solution is to add a hidden field in your form:

另一个可能的解决方案是在表单中添加一个隐藏字段:

<input type="hidden" id="btaction"/>

Then in the ready function add functions to record what key was pressed:

然后在就绪函数中添加函数,记录按下的键:

$('form#myForm #btnSubmit').click(function() {
    $('form#myForm #btaction').val(0);
});

$('form#myForm #btnSubmitAndSend').click(function() {
    $('form#myForm #btaction').val(1);
});

$('form#myForm #btnDelete').click(function() {
    $('form#myForm #btaction').val(2);
});

Now in the form submition handler read the hidden variable and decide based on it:

现在在表单submition handler中读取隐藏变量并根据它做出决定:

var act = $('form#myForm #btaction').val();

#8


6  

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.

建立在Stan和yann-h所做的基础上但是这个是默认的第一个按钮。这种整体方法的优点在于,它同时接收单击和enter键(即使焦点不在按钮上)。如果您需要允许输入表单,那么当按钮被关注时(即Stan的答案),您只需对此做出响应。在我的例子中,我希望允许enter提交表单,即使用户当前的焦点是文本框。

I was also using a 'name' attribute rather than 'id' but this is the same approach.

我还使用了“name”属性而不是“id”,但这是相同的方法。

var pressedButtonName =
     typeof $(":input[type=submit]:focus")[0] === "undefined" ?
     $(":input[type=submit]:first")[0].name :
     $(":input[type=submit]:focus")[0].name;

#9


6  

I have found the best solution is

我找到了最好的解决办法

$(document.activeElement).attr('id')

This not only works on inputs, but it also works on button tags. Also it gets the id of the button.

这不仅适用于输入,也适用于按钮标签。它还获取按钮的id。

#10


4  

If what you mean by not adding a .click event is that you don't want to have separate handlers for those events, you could handle all clicks (submits) in one function:

如果您不添加.click事件的意思是您不想为这些事件拥有单独的处理程序,那么您可以在一个函数中处理所有单击(提交):

$(document).ready(function(){
  $('input[type="submit"]').click( function(event){ process_form_submission(event); } );
});

function process_form_submission( event ) {
  event.preventDefault();
  //var target = $(event.target);
  var input = $(event.currentTarget);
  var which_button = event.currentTarget.value;
  var data = input.parents("form")[0].data.value;
//  var which_button = '?';       // <-- this is what I want to know
  alert( 'data: ' + data + ', button: ' + which_button );
}

#11


4  

This one worked for me

这个对我起作用了。

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

}

#12


3  

$("form input[type=submit]").click(function() {
    $("<input />")
        .attr('type', 'hidden')
        .attr('name', $(this).attr('name'))
        .attr('value', $(this).attr('value'))
    .appendTo(this)
});

add hidden field

添加隐藏字段

#13


3  

For me, the best solutions was this:

对我来说,最好的解决办法是:

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

});

#14


3  

Working with this excellent answer, you can check the active element (the button), append a hidden input to the form, and optionally remove it at the end of the submit handler.

使用这个优秀的答案,您可以检查活动元素(按钮),向表单添加隐藏的输入,并可以在提交处理程序的末尾删除它。

$('form.form-js').submit(function(event){
    var frm = $(this);
    var btn = $(document.activeElement);
    if(
        btn.length &&
        frm.has(btn) &&
        btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&
        btn.is('[name]')
    ){
        frm.append('<input type="hidden" id="form-js-temp" name="' + btn.attr('name') + '" value="' + btn.val() + '">');
    }

    // Handle the form submit here

    $('#form-js-temp').remove();
});

Side note: I personally add the class form-js on all forms that are submitted via JavaScript.

附注:我个人在所有通过JavaScript提交的表单上添加了form-js类。

#15


2  

Similar to Stan answer but :

类似于Stan的回答,但是:

  • if you have more than one button, you have to get only the first button => [0]
  • 如果您有多个按钮,您必须只获得第一个按钮=> [0]
  • if the form can be submitted with the enter key, you have to manage a default => myDefaultButtonId
  • 如果可以使用enter键提交表单,则必须管理一个默认的=> myDefaultButtonId

$(document).on('submit', function(event) {
    event.preventDefault();
    var pressedButtonId = 
         typeof $(":input[type=submit]:focus")[0] === "undefined" ? 
         "myDefaultButtonId" :
         $(":input[type=submit]:focus")[0].id;
    ...
 }

#16


2  

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

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

#17


1  

It helped me https://*.com/a/17805011/1029257

它帮助我https://*.com/a/17805011/1029257

Form submited only after submit button was clicked.

只有在提交按钮被点击后才能提交表单。

var theBtn = $(':focus');
if(theBtn.is(':submit'))
{
  // ....
  return true;
}

return false;

#18


1  

As I can't comment on the accepted answer, I bring here a modified version that should take into account elements that are outside the form (ie: attached to the form using the form attribute). This is for modern browser: http://caniuse.com/#feat=form-attribute . The closest('form') is used as a fallback for unsupported form attribute

由于我无法对已接受的答案进行评论,因此我在这里提供了一个修改后的版本,它应该考虑到表单之外的元素(即:使用表单属性附加到表单上)。这是针对现代浏览器的:http://caniuse.com/#feat=form-attribute。最近的(“form”)用作不支持的form属性的回退

$(document).on('click', '[type=submit]', function() {
    var form = $(this).prop('form') || $(this).closest('form')[0];
    $(form.elements).filter('[type=submit]').removeAttr('clicked')
    $(this).attr('clicked', true);
});

$('form').on('submit', function() {
    var submitter = $(this.elements).filter('[clicked]');
})

#19


0  

I also made a solution, and it works quite well:
It uses jQuery and CSS

我还做了一个解决方案,它工作得很好:它使用jQuery和CSS


First, I made a quick CSS class, this can be embedded or in a seperate file.

首先,我创建了一个快速CSS类,它可以被嵌入或者被分离的文件。

<style type='text/css'>
    .Clicked {
        /*No Attributes*/
    }
</style>


Next, On the click event of a button within the form,add the CSS class to the button. If the button already has the CSS class, remove it. (We don't want two CSS classes [Just in case]).

接下来,在表单中单击按钮的事件上,向按钮添加CSS类。如果按钮已经有CSS类,那么删除它。(我们不需要两个CSS类(以防万一))。

    // Adds a CSS Class to the Button That Has Been Clicked.
    $("form :input[type='submit']").click(function () 
    {
        if ($(this).hasClass("Clicked"))
        {
            $(this).removeClass("Clicked");
        }
        $(this).addClass("Clicked");
    });


Now, test the button to see it has the CSS class, if the tested button doesn't have the CSS, then the other button will.

现在,测试这个按钮,看看它有CSS类,如果测试的按钮没有CSS,那么另一个按钮会。

    // On Form Submit
    $("form").submit(function ()
    {
        // Test Which Button Has the Class
        if ($("input[name='name1']").hasClass("Clicked"))
        {
            // Button 'name1' has been clicked.
        }
        else
        {
           // Button 'name2' has been clicked.
        }
    });

Hope this helps! Cheers!

希望这可以帮助!干杯!

#20


0  

You can create input type="hidden" as holder for a button id information.

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

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

In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.

在这种情况下,表单在提交时传递值“1”(您的按钮的id)。如果在submit(?)之前出现onClick,那么它就可以工作,我不确定它是否总是正确的。

#21


0  

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');
  ... 
});

#22


0  

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.

您可以将type="submit"按钮添加到单击时保存的项中。

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:

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:

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:

愚蠢的CSS:

input {display:block}

#23


-1  

You want to use window.event.srcElement.id like this:

您想要使用window.event.srcElement。id是这样的:

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.

您将得到一个警告,该警告如下:“单击的项目是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.

在改进的示例中,可以添加window.event。到process_form_submission的srcElement,您将获得对调用该过程的任何元素的引用。