Process a Form Submit with Multiple Submit Buttons in Javascript

被刻印的时光 ゝ 提交于 2020-01-11 02:49:07

问题


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!


回答1:


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



回答2:


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.

document.querySelector('#my-form button[value="button-one"]' )



回答3:


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


来源:https://stackoverflow.com/questions/26039603/process-a-form-submit-with-multiple-submit-buttons-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!