Javascript 表单 onSubmit 确定按下了哪个提交按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3577469/
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
Form onSubmit determine which submit button was pressed
提问by McTrafik
I have a form with two submit buttons and some code:
我有一个带有两个提交按钮和一些代码的表单:
HTML:
HTML:
<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />
JavaScript:
JavaScript:
form.onSubmit = function(evnt) {
// Do some asyncrhnous stuff, that will later on submit the form
return false;
}
Of course the two submit buttons accomplish different things. Is there a way to find out in onSubmitwhich button was pressed, so later I could submit by doing thatButton.click()?
当然,这两个提交按钮完成不同的事情。有没有办法找出onSubmit按下了哪个按钮,以便稍后我可以通过执行提交thatButton.click()?
Ideally I would like to not modify the code for the buttons, just have a pure JavaScript addon that has this behavior.
理想情况下,我不想修改按钮的代码,只需要一个具有这种行为的纯 JavaScript 插件。
I know that Firefox has evnt.explicitOriginalTarget, but I can't find anything for other browsers.
我知道 Firefox 有evnt.explicitOriginalTarget,但我找不到其他浏览器的任何内容。
采纳答案by Peter Bailey
Not in the submit event handler itself, no.
不在提交事件处理程序本身中,不。
But what you cando is add click handlers to each submit which will inform the submit handler as to which was clicked.
但是您可以做的是向每个提交添加点击处理程序,这将通知提交处理程序点击了哪个。
Here's a full example (using jQuery for brevity)
这是一个完整的示例(为简洁起见,使用 jQuery)
<html>
<head>
<title>Test Page</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery(function($) {
var submitActor = null;
var $form = $('#test');
var $submitActors = $form.find('input[type=submit]');
$form.submit(function(event) {
if (null === submitActor) {
// If no actor is explicitly clicked, the browser will
// automatically choose the first in source-order
// so we do the same here
submitActor = $submitActors[0];
}
console.log(submitActor.name);
// alert(submitActor.name);
return false;
});
$submitActors.click(function(event) {
submitActor = this;
});
});
</script>
</head>
<body>
<form id="test">
<input type="text" />
<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />
</form>
</body>
</html>
回答by Ali Shakiba
回答by Henrik
Bare bones, but confirmed working, example:
裸露的骨头,但确认工作,例如:
<script type="text/javascript">
var clicked;
function mysubmit() {
alert(clicked);
}
</script>
<form action="" onsubmit="mysubmit();return false">
<input type="submit" onclick="clicked='Save'" value="Save" />
<input type="submit" onclick="clicked='Add'" value="Add" />
</form>
回答by Ben Gripka
All of the answers above are very good but I cleaned it up a little bit.
上面的所有答案都非常好,但我清理了一下。
This solution automatically puts the name of the submit button pressed into the action hidden field. Both the javascript on the page and the server code can check the action hidden field value as needed.
此解决方案会自动将按下的提交按钮的名称放入操作隐藏字段中。页面上的 javascript 和服务器代码都可以根据需要检查操作隐藏字段值。
The solution uses jquery to automatically apply to all submit buttons.
该解决方案使用 jquery 自动应用于所有提交按钮。
<input type="hidden" name="action" id="action" />
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//when a submit button is clicked, put its name into the action hidden field
$(":submit").click(function () { $("#action").val(this.name); });
});
</script>
<input type="submit" class="bttn" value="<< Back" name="back" />
<input type="submit" class="bttn" value="Finish" name="finish" />
<input type="submit" class="bttn" value="Save" name="save" />
<input type="submit" class="bttn" value="Next >>" name="next" />
<input type="submit" class="bttn" value="Delete" name="delete" />
<input type="button" class="bttn" name="cancel" value="Cancel" onclick="window.close();" />
Then write code like this into your form submit handler.
然后将这样的代码写入表单提交处理程序。
if ($("#action").val() == "delete") {
return confirm("Are you sure you want to delete the selected item?");
}
回答by Dutchie432
First Suggestion:
第一个建议:
Create a Javascript Variable that will reference the button clicked. Lets call it buttonIndex
创建一个 Javascript 变量来引用单击的按钮。让我们称之为buttonIndex
<input type="submit" onclick="buttonIndex=0;" name="save" value="Save" />
<input type="submit" onclick="buttonIndex=1;" name="saveAndAdd" value="Save and add another" />
Now, you can access that value. 0 means the save button was clicked, 1 means the saveAndAdd Button was clicked.
现在,您可以访问该值。0 表示单击了保存按钮,1 表示单击了 saveAndAdd 按钮。
Second Suggestion
第二个建议
The way I would handle this is to create two JS functions that handle each of the two buttons.
我处理这个问题的方法是创建两个 JS 函数来处理两个按钮中的每一个。
First, make sure your form has a valid ID. For this example, I'll say the ID is "myForm"
首先,确保您的表单具有有效的 ID。对于这个例子,我会说 ID 是“myForm”
change
改变
<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />
to
到
<input type="submit" onclick="submitFunc();return(false);" name="save" value="Save" />
<input type="submit" onclick="submitAndAddFunc();return(false);" name="saveAndAdd" value="Save and add
the return(false) will prevent your form submission from actually processing, and call your custom functions, where you can submit the form later on.
return(false) 将阻止您的表单提交实际处理,并调用您的自定义函数,您可以稍后在其中提交表单。
Then your functions will work something like this...
然后你的功能将像这样工作......
function submitFunc(){
// Do some asyncrhnous stuff, that will later on submit the form
if (okToSubmit) {
document.getElementById('myForm').submit();
}
}
function submitAndAddFunc(){
// Do some asyncrhnous stuff, that will later on submit the form
if (okToSubmit) {
document.getElementById('myForm').submit();
}
}
回答by Spanky
OP stated he didn't want to modify the code for the buttons. This is the least-intrusive answer I could come up with using the other answers as a guide. It doesn't require additional hidden fields, allows you to leave the button code intact (sometimes you don't have access to what generates it), and gives you the info you were looking for from anywhere in your code...which button was used to submit the form. I haven't evaluated what happens if the user uses the Enter key to submit the form, rather than clicking.
OP 表示他不想修改按钮的代码。这是我可以使用其他答案作为指导提出的最少干扰的答案。它不需要额外的隐藏字段,允许您保持按钮代码完整无缺(有时您无法访问生成它的内容),并为您提供从代码中的任何位置查找的信息......哪个按钮用于提交表单。我还没有评估如果用户使用 Enter 键提交表单而不是单击会发生什么。
<script language="javascript" type="text/javascript">
var initiator = '';
$(document).ready(function() {
$(":submit").click(function() { initiator = this.name });
});
</script>
Then you have access to the 'initiator' variable anywhere that might need to do the checking. Hope this helps.
然后,您可以在任何可能需要进行检查的地方访问“启动器”变量。希望这可以帮助。
~Spanky
~打屁股
回答by McTrafik
I use Ext, so I ended up doing this:
我使用 Ext,所以我最终这样做了:
var theForm = Ext.get("theform");
var inputButtons = Ext.DomQuery.jsSelect('input[type="submit"]', theForm.dom);
var inputButtonPressed = null;
for (var i = 0; i < inputButtons.length; i++) {
Ext.fly(inputButtons[i]).on('click', function() {
inputButtonPressed = this;
}, inputButtons[i]);
}
and then when it was time submit I did
然后到了提交的时候我做了
if (inputButtonPressed !== null) inputButtonPressed.click();
else theForm.dom.submit();
Wait, you say. This will loop if you're not careful. So, onSubmit must sometimes return true
等等,你说。如果您不小心,这将循环。所以,onSubmit 有时必须返回 true
// Notice I'm not using Ext here, because they can't stop the submit
theForm.dom.onsubmit = function () {
if (gottaDoSomething) {
// Do something asynchronous, call the two lines above when done.
gottaDoSomething = false;
return false;
}
return true;
}
回答by palswim
Why not loop through the inputs and then add onclick handlers to each?
为什么不遍历输入,然后为每个输入添加 onclick 处理程序?
You don't have to do this in HTML, but you can add a handler to each button like:
您不必在 HTML 中执行此操作,但您可以为每个按钮添加一个处理程序,例如:
button.onclick = function(){ DoStuff(this.value); return false; } // return false; so that form does not submit
Then your function could "do stuff" according to whichever value you passed:
然后你的函数可以根据你传递的任何值“做事”:
function DoStuff(val) {
if( val === "Val 1" ) {
// Do some stuff
}
// Do other stuff
}

