使用JavaScript处理带有多个提交按钮的表单提交 [英] Process a Form Submit with Multiple Submit Buttons in Javascript

查看:128
本文介绍了使用JavaScript处理带有多个提交按钮的表单提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个提交按钮的表单,我想捕获按下任何一个提交按钮时的情况,并为每个按钮执行不同的JS代码.

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.

<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>

查看旧答案,我可以处理JS中所有 提交按钮:

Looking at an older answer, I can process all of the submit buttons in 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);
}

但是如何区分不同的提交按钮?是否可以从中获取value并执行逻辑?

But how can I discriminate amongst the different submit buttons? Is there a way to get the value and perform logic from there?

我本身不需要三个 submit 按钮...我只需要一个表单中的三个不同按钮即可执行三个不同的动作.

I don't need to have three submit buttons, per se... I just need three different buttons in a form to perform three different actions.

谢谢!

推荐答案

您可以将自定义点击处理程序附加到所有按钮,这样您可以在提交表单之前检查单击了哪个按钮:

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
});

这篇关于使用JavaScript处理带有多个提交按钮的表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆