-1

I'm trying to do something simple, there are 3 checkboxes and when I click on one I want the rest of them to be deselected. I also want to use a methods that I wrote for this purpose to be used on click.

when I do

myCheckBox.onclick = myMethod(); 

it runs only once when page loads and generally is not working properly

but when I do

myCheckBox.onclick = function(){
   myMethod();
};

everything works as intended. Why does it work like this?

  • `myCheckBox.onclick = myMethod; ` this is how point to a function reference. By using `()` at the end, the function will execute and the `onclick` will receive its return value. – DontVoteMeDown Jun 11 '19 at 19:31
  • When you add parens after a function like `myMethod()`, it executes the function and the *return value* is used. So, assuming `myMethod()` returns `"Hello"`, the line `myCheckBox.onclick = myMethod();` is equivalent to `myCheckBox.onclick = "hello"`. Instead, you don't want to execute the function, you want to point at the **definition** of the function, ie `myCheckBox.onclick = myMethod`. Your second example points at the definition of a new, anonymous function that executes `myMethod()`. – Tyler Roper Jun 11 '19 at 19:33

2 Answers2

1

You need to do

myCheckBox.onclick = myMethod; 

To assign the method to the event.

When you run myMethod() it would apply whatever myMethod returns to the onclick event listener

Zachary Brooks
  • 303
  • 2
  • 9
1

You'll want to use:

myCheckBox.onclick = myMethod;
MattB
  • 1,104
  • 8
  • 15