jQuery:如何获取表单提交时点击了哪个按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5721724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: how to get which button was clicked upon form submission?
提问by hawkexp
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>
Besides applying a .click() event on each button, is there a way to determine which submit button was clicked?
除了在每个按钮上应用 .click() 事件之外,有没有办法确定点击了哪个提交按钮?
回答by hunter
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
在您有多种形式的情况下,您可能需要稍微调整一下,但它仍然适用
回答by Stan
I found that this worked.
我发现这有效。
$(document).ready(function() {
$( "form" ).submit(function () {
// Get the submit button element
var btn = $(this).find("input[type=submit]:focus" );
});
}
回答by seddonym
This works for me:
这对我有用:
$("form").submit(function() {
// Print the value of the button that was clicked
console.log($(document.activeElement).val());
}
回答by Nick F
When the form is submitted:
提交表单时:
document.activeElement
will give you the submit button that was clicked.document.activeElement.getAttribute('value')
will give you that button's value.
document.activeElement
会给你点击的提交按钮。document.activeElement.getAttribute('value')
会给你那个按钮的价值。
回答by Jonathan Camenisch
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();
回答by lawnbowler
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') 进一步过滤许多表单之一的 $('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);
});
});
回答by Thomas Williams
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。
回答by wmac
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:
然后在 ready 函数中添加函数来记录按下了什么键:
$('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:
现在在表单提交处理程序中读取隐藏变量并根据它做出决定:
var act = $('form#myForm #btaction').val();
回答by andrewmo
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 所做的基础上,但这个默认为第一个按钮。这种整体方法的美妙之处在于它同时选择了单击和回车键(即使焦点不在按钮上。如果您需要允许在表单中输入,那么只需在按钮获得焦点时响应即可( ie Stan's answer). 就我而言,即使用户当前的焦点在文本框上,我也希望允许 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;
回答by Saheb Mondal
This one worked for me
这个对我有用
$('#Form').submit(function(){
var btn= $(this).find("input[type=submit]:focus").val();
alert('you have clicked '+ btn);
}