Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
785 views
in Technique[技术] by (71.8m points)

jquery - Process a Form Submit with Multiple Submit Buttons in Javascript

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>

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

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

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.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can attach a custom click handler to all buttons, and that way you can check which button is clicked before submitting the form:

Live Example

$("#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
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...