0

I have the below code. All I want to do is do different work based on the radio button value selected, and I am using onclick.

/* HTML */

<input label='radio' id='radioYes' name='selectionA' value='yes'>
<input label='radio' id='radioNo' name='selectionA' value='no'>

/* JavaScript */

(function(){
     var obj = {
         start: function(){
              /* Do some work */

              this.addEvents();

              /* Do some work */
         },
         addEvents: function(){
             document.getElementById('radioYes').onclick = function() {this.radioClicked(true);};
             document.getElementById('radioNo').onclick = function() {this.radioClicked(false);};
         },
         radioClicked: function(bool){
             if(bool){
                  /*Yes was selected. Do some work.*/
             }
             else{
                  /*No was selected. Do some work.*/
             }
         }
     };
     obj.start();     
}();    

When I click on the radio button, I get TypeError: this.radioClicked is not a function but I can't figure out why. The function 'radioClicked' is defined right below!

When I do the following without any parameters, it works fine.

     addEvents: function(){
         document.getElementById('radioYes').onclick = this.radioClicked;
         document.getElementById('radioNo').onclick = this.radioClicked;
     },
     radioClicked: function(){
          /* Do some work */
     }

I read on some website that if you want to pass parameters, you can put your function inside an anonymous function like I did in the first code that's not working. Could someone please help me what I am doing here?

J.Doe
  • 329
  • 3
  • 14
  • 2
    In an event listener, `this` is the target of the event, not `obj`. – Barmar Sep 23 '21 at 23:26
  • Thank you @Barmar! I did not know that. What confused me more was the fact that this.radioClicked worked fine, but this.radioClicked(true) didn't work. I just changed `this` to `obj` and it is working now. I really appreciate your help. – J.Doe Sep 23 '21 at 23:28

0 Answers0