Process A Form Submit With Multiple Submit Buttons In Javascript August 31, 2023 Post a Comment 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 }); CopySolution 2: use thisfunctionprocessForm(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; } CopySolution 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>CopyJS:consthandleSubmit = e => { e.preventDefault(); var ans = document.activeElement['value']; console.log(ans); }; CopySolution 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"]' ) Copy Share Post a Comment for "Process A Form Submit With Multiple Submit Buttons In Javascript"
Post a Comment for "Process A Form Submit With Multiple Submit Buttons In Javascript"