Skip to content Skip to sidebar Skip to footer

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.

Solution 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 submissionif($(this).attr("value")=="button-one"){
        //do button 1 thing
    }
    // $("#my-form").submit(); if you want to submit the form
});

Solution 2:

use this

functionprocessForm(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 behaviorreturnfalse;
}

Solution 3:

HTML:

<formid = "form"onSubmit = {handleSubmit}><inputtype="email"name="email"placeholder="(Your email)" /><buttontype="submit"value="button-one">Go - One</button><buttontype="submit"value="button-two">Go - Two</button><buttontype="submit"value="button-three">Go - Three</button></form>

JS:

consthandleSubmit = e => {
    e.preventDefault();

    var ans = document.activeElement['value'];
    console.log(ans);
};

Solution 4:

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"]' )

Post a Comment for "Process A Form Submit With Multiple Submit Buttons In Javascript"