Reputation: 910
I have 3 buttons on my web page called btn_newsletter_wide
, btn_newsletter_desktop
and btn_newsletter_mobile
that should submit a form, but before doing so I want to apply some specific validation depending on the button pressed. All the buttons have an onclick action to one function that determines the validation to apply via a Switch select as below;
function validate_forms() {
var btnSelected = (this.id)
switch (btnSelected) {
case "btn_newsletter_wide":
validate_form_newsletter_wide( form );
break;
case "btn_newsletter_desktop":
validate_form_newsletter_wide( form );
break;
case "btn_newsletter_mobile":
validate_form_newsletter_wide( form );
break;
}
}
But does not seem to work, on debugging it I find that btnSelected=undefined
so the calls to the right function don't happen. So it must be something with the way that I am trying to pass the ID of the button selected to the variable, after some tinkering I can't correct it.
Can someone point me in the right direction please.
Upvotes: 0
Views: 2153
Reputation: 9393
If your inlining the event on button you must explcitly pass this object reference
<button id="yourbutton" onclick="validate_form(this)"> // pass this object explicitly
// or addEventListener more recommended way to do
document.getElementById("yourbutton").addEventListener("click", validate_form);
// or attach onclick event
document.getElementById("yourbutton").onclick = validate_form;
To attach same function for multiple elements see this link JavaScript click event listener on class
Upvotes: 1