Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the difference between .click and .change on a checkbox [duplicate]

I was looking around to add an event to a checkbox and I would have thought people would use .change to set up a change event but instead I found that people are using .click

Is there a reason for this? They both seem to work fine both with clicked events and with keyboard changes. Am I missing something?

If you don't believe me then try it out yourself

like image 885
qwertymk Avatar asked Apr 07 '11 02:04

qwertymk


2 Answers

onchange in IE only fires when the checkbox loses focus. So if you tab to it, hit space a few times, tab out, you'll only get one onchange event, but several onclick events.

Note: this is one of the very, very, very rare times when IE's behavior is correct (according to spec) and other browsers are wrong.

like image 182
Nobody Avatar answered Oct 02 '22 21:10

Nobody


Two reasons why onclick is preferred over onchange.

  1. Internet Explorer only fires the onchange event when the checkbox loses the focus (onblur). So onclick is more of a cross browser solution.

  2. onchange happens only after the element lose focus.(You wont see a difference since you are calling alert and losing focus on every change). The pseudo code on MDC pretty much explains the element.onchange implementation.

    control.onfocus = focus; control.onblur = blur;  function focus () {     original_value = control.value; }  function blur () {     if (control.value != original_value)         control.onchange(); } 
like image 37
naveen Avatar answered Oct 02 '22 21:10

naveen