0

Today I was writing code that is running code if a person clicks a checbox.

I wrote the code like this:

$(".checkbox").on( "click", function() {
    //code
});

I could also write the code like this:

$(".checkbox").on( "change", function() {
    //code
});

Both achieve the same end I am looking to achieve but should I use one over the other?

L84
  • 45,514
  • 58
  • 177
  • 257

2 Answers2

10

You should use change, since a checkbox can be changed via a keyboard (tab to element, press space). Also, it can be changed from some other Javascript code (in the future), or via a label being clicked if that label is 'attached' to the checkbox.

L84
  • 45,514
  • 58
  • 177
  • 257
Hamza Kubba
  • 2,259
  • 14
  • 12
1

Form elements raise onchange events whenever the user changes their values. Like the other answer says, this can be due to mouse clicks or key presses.

Any element that takes up screen space will raise an onclick event whenever the user clicks on it. The callback you provide is given an argument that contains the cursor's X and Y coordinates and some other stuff.

It just so happens that when you click a checkbox, that changes its value, so both onclick and onchange events are raised.

You should use whichever event best matches the effect you want on your page.

jcarpenter2
  • 5,312
  • 4
  • 22
  • 49