在 Javascript 中使用多个提交按钮处理表单提交
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26039603/
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
Process a Form Submit with Multiple Submit Buttons in Javascript
提问by Berto
I have a form with multiple submit buttons, and I'd like to capture when any of them are pressed, and perform different JS code for each one.
我有一个带有多个提交按钮的表单,我想在按下任何一个按钮时进行捕获,并为每个按钮执行不同的 JS 代码。
<form id="my-form">
<input type="email" name="email" placeholder="(Your email)" />
<button type="submit" value="button-one">Go - One</button>
<button type="submit" value="button-two">Go - Two</button>
<button type="submit" value="button-three">Go - Three</button>
</form>
Looking at an older answer, I can process allof the submit buttons in JS:
查看旧答案,我可以处理JS中的所有提交按钮:
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
// You must return false to prevent the default form behavior
return false;
}
var form = document.getElementById('my-form');
if (form.attachEvent) {
form.attachEvent("submit", processForm);
} else {
form.addEventListener("submit", processForm);
}
But how can I discriminate amongst the different submit buttons?Is there a way to get the value
and perform logic from there?
但是我如何区分不同的提交按钮?有没有办法value
从那里获取并执行逻辑?
I don't need to have three submitbuttons, per se... I just need three different buttons in a form to perform three different actions.
我不需要三个提交按钮,本身...我只需要在一个表单中使用三个不同的按钮来执行三个不同的操作。
Thanks!
谢谢!
采纳答案by Banana
you can attach a custom click handler to all buttons, and that way you can check which button is clicked before submitting the form:
您可以将自定义单击处理程序附加到所有按钮,这样您就可以在提交表单之前检查单击了哪个按钮:
$("#my-form button").click(function(ev){
ev.preventDefault()// cancel form submission
if($(this).attr("value")=="button-one"){
//do button 1 thing
}
// $("#my-form").submit(); if you want to submit the form
});
回答by aM-Vee
use this
用这个
function processForm(e) {
if (e.preventDefault) e.preventDefault();
/* do what you want with the form */
var submit_type = document.getElementById('my-form').getAttribute("value");
if(submit_type=="button-one"){
}//and so on
// You must return false to prevent the default form behavior
return false;
}
回答by Matt Styles
But how can I discriminate amongst the different submit buttons? Is there a way to get the value and perform logic from there?
但是我如何区分不同的提交按钮?有没有办法从那里获取价值并执行逻辑?
Yes, you can use querySelector
to grab elements with attributes.
是的,您可以querySelector
用来抓取具有属性的元素。
document.querySelector('#my-form button[value="button-one"]' )