0

My JS goes here <input type='radio'id="Hero"/> the bunch of functions below get the radio button get unchecked whenever it gets clicked even time

var hero=document.getElementById('Hero');

hero.addEventListener('onclick',"bye(this)");
  
function bye(this){
    var check=this.id; /////Here I am getting  the id of the element
    hoya(); 
   if(c%2==0){
    check.checked=false;
   }
}

function hoya(){
  ++c;
  return c; 
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    Because the second argument of `addEventListener` needs to be a function. `"bye(this)"` is not a function. – Sebastian Simon Feb 28 '17 at 19:20
  • Sir it is a function you may look – Suyash Srivastava Feb 28 '17 at 19:23
  • No, it’s not a function. It’s a string. – Sebastian Simon Feb 28 '17 at 19:24
  • Ok should i pass it without quotes – Suyash Srivastava Feb 28 '17 at 19:28
  • But sir if you say so i agree but in this case it works with quotes

    When you select a new car, a function is triggered which outputs the value of the selected car.

    – Suyash Srivastava Feb 28 '17 at 19:30
  • 1
    `addEventListener` is not the same thing as an inline event listener (HTML attribute). Passing it without quotes also will not work, because `bye(this)` is also not a function. This is how you need to do it: [How to pass parameter to function using in addEventListener?](http://stackoverflow.com/q/12024483/4642212). – Sebastian Simon Feb 28 '17 at 19:38
  • @SuyashSrivastava When you add it in as an attribute to HTML that attribute is evaluated by the JavaScript parser. When you pass a function as a parameter within JavaScript it has to explicitly be a function, not a string. – zfrisch Feb 28 '17 at 19:40
  • @SuyashSrivastava It seems you are probably new to JS, as a suggestion, it is best to avoid inline events for a number of reasons. As evidenced by your confusion, code maintenance and clarity can suffer. – zfrisch Feb 28 '17 at 19:43
  • Check the docs for [functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions) and [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener). `"bye(this)"` is a string, `bye(this)` is `undefined` because `bye` doesn’t return anything. `bye`, `function(){ bye(this); }`* and `bye.bind(this)` are functions (* in expression context). You want one of the three last ones. – Sebastian Simon Feb 28 '17 at 19:47

0 Answers0