Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  120] [ 6]  / answers: 1 / hits: 23145  / 10 Years ago, thu, september 25, 2014, 12:00:00

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!


More From » jquery

 Answers
2

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

[#69338] Tuesday, September 23, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tylerdamiena

Total Points: 139
Total Questions: 90
Total Answers: 118

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
tylerdamiena questions
;