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

Solution 2:

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

Solution 3:

HTML:

<form id = "form" onSubmit = {handleSubmit}>
<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:

const handleSubmit = 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"