jQuery 如何从表单提交事件中获取导致提交的按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2066162/
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
How can I get the button that caused the submit from the form submit event?
提问by hunter
I'm trying to find the value of the submit button that triggered the form to submit
我试图找到触发表单提交的提交按钮的值
$("form").submit(function() {
});
I could possibly fire a $("input[type=submit]").click() event for each button and set some variable, but that seems less elegant than some how pulling the button off of the the form on submit.
我可能会为每个按钮触发 $("input[type=submit]").click() 事件并设置一些变量,但这似乎不如在提交时将按钮从表单中拉出那样优雅。
采纳答案by hunter
I implemented this and I suppose it will do.
我实现了这个,我想它会做。
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val()
// DO WORK
});
and this is the submit button event that sets it up
这是设置它的提交按钮事件
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
Thanks for the responses, but this isn't terribly inelegant...
感谢您的回复,但这并不是非常不雅......
回答by Boldewyn
I leveraged document.activeElement
as sketched in this answer: How to get the focused element with jQuery?
我利用document.activeElement
了这个答案中的草图:How to get the focus element with jQuery?
$form.on('submit', function() {
var $btn = $(document.activeElement);
if (
/* there is an activeElement at all */
$btn.length &&
/* it's a child of the form */
$form.has($btn) &&
/* it's really a submit element */
$btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&
/* it has a "name" attribute */
$btn.is('[name]')
) {
console.log("Seems, that this element was clicked:", $btn);
/* access $btn.attr("name") and $btn.val() for data */
}
});
I take advantage of the fact, that the button is always the focused element after clicking it. This will notwork, if you do a blur()
right after the click.
我利用了这样一个事实,即按钮在单击后始终是焦点元素。这将不会工作,如果你做一个blur()
点击之后。
@Doin has spotted another drawback. If a user submits the form via enter
in a text field, the document.activeElement
is not set. You'd need to watch out for this yourself, by handling keypress
events in input[type="text"]
and similar.
@Doin 发现了另一个缺点。如果用户通过enter
文本字段提交表单,document.activeElement
则不会设置。你需要自己注意这一点,通过处理和类似的keypress
事件input[type="text"]
。
Update 2017-01:For my library HyperformI chose not to use activeElement
but to catch all events, that lead to form submission. The code for thisis on Github.
2017-01 更新:对于我的库Hyperform,我选择不使用activeElement
而是捕获所有导致表单提交的事件。这个代码在 Github 上。
If you happen to use Hyperform, this is how you would access the button that triggered the submit:
如果您碰巧使用 Hyperform,这就是您访问触发提交的按钮的方式:
$(form).on('submit', function(event) {
var button = event.submittedVia;
});
回答by Dave Anderson
I created a test form and using Firebug found this way to get the value;
我创建了一个测试表单,并使用 Firebug 找到了这种获取值的方式;
$('form').submit(function(event){
alert(event.originalEvent.explicitOriginalTarget.value);
});
Unfortunately, only Firefox supports this event.
不幸的是,只有 Firefox 支持这个事件。
回答by Jonathan Camenisch
Here's an 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 cmptrgeekken
According to this link, the Event object contains a field Event.target
, which:
根据此链接,事件对象包含一个字段Event.target
,其中:
Returns a string representing the object that initiated the event.
返回一个表示发起事件的对象的字符串。
I just created a page testing out what that value is, and it appears as though that representation is for the form itself, not for the button clicked. In other words, Javascript doesn't provide the facility to determine the clicked button.
我刚刚创建了一个页面来测试该值是什么,看起来好像该表示是针对表单本身的,而不是针对单击的按钮。换句话说,Javascript 不提供工具来确定单击的按钮。
As far as Dave Anderson's solution, it might be a good idea to test that in multiple browsers before using it. It's possible that it could work fine, but I can't say either way.
至于戴夫安德森的解决方案,在使用它之前在多个浏览器中测试它可能是一个好主意。有可能它可以正常工作,但我不能说任何一种方式。
回答by user1128563
One clean approach is to use the click event on each form button. Following is a html form with save,cancel and delete buttons:
一种干净的方法是在每个表单按钮上使用单击事件。以下是一个带有保存、取消和删除按钮的 html 表单:
<form name="formname" action="/location/form_action" method="POST">
<input name="note_id" value="some value"/>
<input class="savenote" type="submit" value="Save"/>
<input class="cancelnote" type="submit" value="Cancel"/>
<input class="deletenote" type="submit" value="Delete" />
</form>
Following is the jquery. I send the appropriate 'action' to the same server function depending on which button was clicked ('save' or 'delete'). If 'cancel', is clicked, I just reload the page.
以下是jquery。我根据单击的按钮(“保存”或“删除”)将适当的“操作”发送到相同的服务器功能。如果单击“取消”,我只需重新加载页面。
$('.savenote').click(function(){
var options = {
data: {'action':'save'}
};
$(this).parent().ajaxSubmit(options);
});
$('.deletenote').click(function(){
var options = {
data: {'action':'delete'}
};
$(this).parent().ajaxSubmit(options);
});
$('.cancelnote').click(function(){
window.location.reload(true);
return false;
});
回答by Tobias Buschor
There is now a standard submitter
property in the submit event.
Already implemented in firefox!
现在submitter
提交事件中有一个标准属性。
已经在火狐中实现了!
document.addEventListener('submit',function(e){
console.log(e.submitter)
})
for browsers not supporting it use this polyfill:
对于不支持它的浏览器,请使用这个 polyfill:
!function(){
var lastBtn = null
document.addEventListener('click',function(e){
if (!e.target.closest) return;
lastBtn = e.target.closest('button, input[type=submit]');
}, true);
document.addEventListener('submit',function(e){
if (e.submitter) return;
var canditates = [document.activeElement, lastBtn];
for (var i=0; i < canditates.length; i++) {
var candidate = canditates[i];
if (!candidate) continue;
if (!candidate.form) continue;
if (!candidate.matches('button, input[type=button], input[type=image]')) continue;
e.submitter = candidate;
return;
}
e.submitter = e.target.querySelector('button, input[type=button], input[type=image]')
}, true);
}();
回答by J. Bruni
I searched and found several ways to get the submit button name
+ value
sent to the server using jQuery + AJAX. I didn't like them very much...
我搜索并找到了几种使用jQuery + AJAX将提交按钮name
+value
发送到服务器的方法。我不是很喜欢他们...
One of the bests was hunter's solution presented here!
最好的方法之一是这里介绍的猎人解决方案!
But I wrote another one myself.
但是我自己又写了一篇。
I want to share, because it is good, and, as I needed, it works also with forms loaded via ajax (after document.ready):
我想分享,因为它很好,而且,根据我的需要,它也适用于通过 ajax 加载的表单(在 document.ready 之后):
$(document).on('click', 'form input[type=submit]', function(){
$('<input type="hidden" />').appendTo($(this).parents('form').first()).attr('name', $(this).attr('name')).attr('value', $(this).attr('value'));
});
Simple! When the submit button is clicked, a hidden field is added to the form, using same name
and value
of the submit button.
简单的!当提交按钮被点击时,一个隐藏字段被添加到表单中,使用与提交按钮相同的name
和value
。
EDIT:The version below is easier to read. Also, it takes care of removing previously appended hidden fields (in the case of submitting the same form twice, which is perfectly possible when using AJAX).
编辑:下面的版本更容易阅读。此外,它还负责删除以前附加的隐藏字段(在两次提交相同表单的情况下,这在使用 AJAX 时是完全可能的)。
Improved code:
改进的代码:
$(document).on('click', 'form input[type=submit]', function(){
var name = $(this).attr('name');
if (typeof name == 'undefined') return;
var value = $(this).attr('value');
var $form = $(this).parents('form').first();
var $input = $('<input type="hidden" class="temp-hidden" />').attr('name', name).attr('value', value);
$form.find('input.temp-hidden').remove();
$form.append($input);
});
回答by Rudi Strydom
I did try some of the examples provided, but they didn't work for our purposes.
我确实尝试了提供的一些示例,但它们不适合我们的目的。
Here's a fiddle to show: http://jsfiddle.net/7a8qhofo/1/
这是一个要显示的小提琴:http: //jsfiddle.net/7a8qhofo/1/
I was faced with a similar issue, and this is how we solved the issue in our forms.
我遇到了类似的问题,这就是我们在表单中解决问题的方式。
$(document).ready(function(){
// Set a variable, we will fill later.
var value = null;
// On submit click, set the value
$('input[type="submit"]').click(function(){
value = $(this).val();
});
// On data-type submit click, set the value
$('input[type="submit"][data-type]').click(function(){
value = $(this).data('type');
});
// Use the set value in the submit function
$('form').submit(function (event){
event.preventDefault();
alert(value);
// do whatever you need to with the content
});
});
回答by user3126867
( event )
( 事件 )
function submForm(form,event){
var submitButton;
if(typeof event.explicitOriginalTarget != 'undefined'){ //
submitButton = event.explicitOriginalTarget;
}else if(typeof document.activeElement.value != 'undefined'){ // IE
submitButton = document.activeElement;
};
alert(submitButton.name+' = '+submitButton.value)
}
<form action="" method="post" onSubmit="submForm(this, event); return false;">