I'm trying to find the value of the submit button that triggered the form to submit
我正在尝试查找触发提交表单的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()事件并设置一些变量,但这似乎不如在submit上从表单中拉下按钮来得优雅。
13 个解决方案
#1
90
I leveraged document.activeElement
as sketched in this answer: How to get the focused element with jQuery?
我利用文档。如本文所述,activeElement:如何使用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 not work, 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提交表单,文档。activeElement没有设置。您需要自己注意这一点,通过处理输入[type="text"]和类似的按键事件。
Update 2017-01: For my library Hyperform I chose not to use activeElement
but to catch all events, that lead to form submission. The code for this is on Github.
更新2017-01:对于我的库hyperformance,我选择不使用activeElement,而是捕捉所有导致表单提交的事件。这个代码在Github上。
If you happen to use Hyperform, this is how you would access the button that triggered the submit:
如果您碰巧使用hyperformance,这是您访问触发提交的按钮的方式:
$(form).on('submit', function(event) {
var button = event.submittedVia;
});
#2
32
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
这是设置它的submit按钮事件
$("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...
谢谢你的回复,但这并不是很不优雅……
#3
9
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支持这个事件。
#4
6
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();
#5
4
According to this link, the Event object contains a field Event.target
, which:
根据这个链接,事件对象包含一个字段事件。目标,它:
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.
至于Dave Anderson的解决方案,在使用它之前最好在多个浏览器中进行测试。这可能行得通,但我说不准。
#6
4
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。我将适当的“动作”发送到相同的服务器函数,这取决于单击了哪个按钮(“保存”或“删除”)。如果“cancel”被单击,我将重新加载页面。
$('.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;
});
#7
3
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将提交按钮名称+值发送到服务器。我不太喜欢他们……
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.
简单!单击submit按钮时,将使用submit按钮的相同名称和值向表单添加一个隐藏字段。
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);
});
#8
2
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
});
});
#9
1
you can try this way with "event.originalEvent.x" and "event.originalEvent.y":
您可以尝试使用“event.originalEvent”。x”和“event.originalEvent.y”:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>test</title>
</head>
<body>
<form id="is_a_form">
<input id="is_a_input_1" type="submit"><br />
<input id="is_a_input_2" type="submit"><br />
<input id="is_a_input_3" type="submit"><br />
<input id="is_a_input_4" type="submit"><br />
<input id="is_a_input_5" type="submit"><br />
</form>
</body>
</html>
<script>
$(function(){
$.fn.extend({
inPosition: function(x, y) {
return this.each(function() {
try{
var offset = $(this).offset();
if ( (x >= offset.left) &&
(x <= (offset.left+$(this).width())) &&
(y >= offset.top) &&
(y <= (offset.top+$(this).height())) )
{
$(this).css("background-color", "red");
}
else
{
$(this).css("background-color", "#d4d0c8");
}
}
catch(ex)
{
}
});
}
});
$("form").submit(function(ev) {
$("input[type='submit']").inPosition(ev.originalEvent.x ,ev.originalEvent.y);
return false;
});
});
</script>
#10
0
jQuery doesn't seem to provide that data on the submit event. Looks like the method you proposed is your best bet.
jQuery似乎没有提供提交事件的数据。看来你提出的方法是你的最佳选择。
#11
0
Just another solution since no other met my requirements. The advantage is, that click and keypress (enter and space) are detected.
这只是另一个解决方案,因为没有其他方案符合我的要求。优点是,可以检测到单击和按下键(输入和空格)。
// Detects the Events
var $form = $('form');
$form.on('click keypress', 'button[type="submit"]', function (ev) {
// Get the key (enter, space or mouse) which was pressed.
if (ev.which === 13 || ev.which === 32 || ev.type === 'click') {
// Get the clicked button
var caller = ev.currentTarget;
// Input Validation
if (!($form.valid())) {
return;
}
// Do whatever you want, e.g. ajax...
ev.preventDefault();
$.ajax({
// ...
})
}
}
This worked best for me.
这对我最有效。
#12
0
( 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;">
#13
0
With a more specific event handler and JQuery, your event object is the button clicked. You can also get the delegating form from this event if needed.
使用更特定的事件处理程序和JQuery,您的事件对象是单击的按钮。如果需要,还可以从这个事件中获得委托表单。
$('form').on('click', 'button', function (e) {
e.preventDefault();
var
$button = $(e.target),
$form = $(e.delegateTarget);
var buttonValue = $button.val();
});
This Doc has everything you need to get started. JQuery Doc.
这个医生有一切你需要的开始。JQuery文档。
#1
90
I leveraged document.activeElement
as sketched in this answer: How to get the focused element with jQuery?
我利用文档。如本文所述,activeElement:如何使用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 not work, 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提交表单,文档。activeElement没有设置。您需要自己注意这一点,通过处理输入[type="text"]和类似的按键事件。
Update 2017-01: For my library Hyperform I chose not to use activeElement
but to catch all events, that lead to form submission. The code for this is on Github.
更新2017-01:对于我的库hyperformance,我选择不使用activeElement,而是捕捉所有导致表单提交的事件。这个代码在Github上。
If you happen to use Hyperform, this is how you would access the button that triggered the submit:
如果您碰巧使用hyperformance,这是您访问触发提交的按钮的方式:
$(form).on('submit', function(event) {
var button = event.submittedVia;
});
#2
32
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
这是设置它的submit按钮事件
$("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...
谢谢你的回复,但这并不是很不优雅……
#3
9
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支持这个事件。
#4
6
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();
#5
4
According to this link, the Event object contains a field Event.target
, which:
根据这个链接,事件对象包含一个字段事件。目标,它:
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.
至于Dave Anderson的解决方案,在使用它之前最好在多个浏览器中进行测试。这可能行得通,但我说不准。
#6
4
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。我将适当的“动作”发送到相同的服务器函数,这取决于单击了哪个按钮(“保存”或“删除”)。如果“cancel”被单击,我将重新加载页面。
$('.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;
});
#7
3
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将提交按钮名称+值发送到服务器。我不太喜欢他们……
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.
简单!单击submit按钮时,将使用submit按钮的相同名称和值向表单添加一个隐藏字段。
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);
});
#8
2
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
});
});
#9
1
you can try this way with "event.originalEvent.x" and "event.originalEvent.y":
您可以尝试使用“event.originalEvent”。x”和“event.originalEvent.y”:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>test</title>
</head>
<body>
<form id="is_a_form">
<input id="is_a_input_1" type="submit"><br />
<input id="is_a_input_2" type="submit"><br />
<input id="is_a_input_3" type="submit"><br />
<input id="is_a_input_4" type="submit"><br />
<input id="is_a_input_5" type="submit"><br />
</form>
</body>
</html>
<script>
$(function(){
$.fn.extend({
inPosition: function(x, y) {
return this.each(function() {
try{
var offset = $(this).offset();
if ( (x >= offset.left) &&
(x <= (offset.left+$(this).width())) &&
(y >= offset.top) &&
(y <= (offset.top+$(this).height())) )
{
$(this).css("background-color", "red");
}
else
{
$(this).css("background-color", "#d4d0c8");
}
}
catch(ex)
{
}
});
}
});
$("form").submit(function(ev) {
$("input[type='submit']").inPosition(ev.originalEvent.x ,ev.originalEvent.y);
return false;
});
});
</script>
#10
0
jQuery doesn't seem to provide that data on the submit event. Looks like the method you proposed is your best bet.
jQuery似乎没有提供提交事件的数据。看来你提出的方法是你的最佳选择。
#11
0
Just another solution since no other met my requirements. The advantage is, that click and keypress (enter and space) are detected.
这只是另一个解决方案,因为没有其他方案符合我的要求。优点是,可以检测到单击和按下键(输入和空格)。
// Detects the Events
var $form = $('form');
$form.on('click keypress', 'button[type="submit"]', function (ev) {
// Get the key (enter, space or mouse) which was pressed.
if (ev.which === 13 || ev.which === 32 || ev.type === 'click') {
// Get the clicked button
var caller = ev.currentTarget;
// Input Validation
if (!($form.valid())) {
return;
}
// Do whatever you want, e.g. ajax...
ev.preventDefault();
$.ajax({
// ...
})
}
}
This worked best for me.
这对我最有效。
#12
0
( 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;">
#13
0
With a more specific event handler and JQuery, your event object is the button clicked. You can also get the delegating form from this event if needed.
使用更特定的事件处理程序和JQuery,您的事件对象是单击的按钮。如果需要,还可以从这个事件中获得委托表单。
$('form').on('click', 'button', function (e) {
e.preventDefault();
var
$button = $(e.target),
$form = $(e.delegateTarget);
var buttonValue = $button.val();
});
This Doc has everything you need to get started. JQuery Doc.
这个医生有一切你需要的开始。JQuery文档。