0

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.

augustoccesar
  • 658
  • 9
  • 30
Naz
  • 900
  • 2
  • 10
  • 25
  • where do you call `validate_forms`, include the code? – depperm Sep 15 '15 at 18:06
  • pass this in validate_forms(). Example: validate_forms(this) – JGV Sep 15 '15 at 18:11
  • You should be getting "event" object inside the click handler which will have "target" property which will refer to the actual node being clicked. That should help – Tarang Sep 15 '15 at 18:12

1 Answers1

1

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

Community
  • 1
  • 1
niko
  • 9,285
  • 27
  • 84
  • 131