Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery difference between change and click event of checkbox

As title suggests I want to know the difference between the change and click event of checkbox (in jQuery)

I have read down the answer to this What the difference between .click and .change on a checkbox

But, its not working for me. change fires even when I hit spaces without losing focus.

Here's a fiddle demo

Both seems to be working alike. Am I missing something here ?

like image 459
Jashwant Avatar asked Jun 26 '12 11:06

Jashwant


People also ask

What is the difference between on click and click in jQuery?

on() differs from . click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas . click() does not. When .

Which event is triggered when the user clicks in a check box?

When the check box is clicked, the event procedure checks whether the check box is being selected or cleared and then sets the text box's properties to enable or disable editing accordingly.

What is the difference between change and Onchange?

The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed.


1 Answers

According to the W3C, the onclick event is triggered by the keyboard for accessibility purposes:

SCR35: Making actions keyboard accessible by using the onclick event of anchors and buttons

In order to provide a better user experience for those without the use of a mouse, browsers have been developed to fire the onclick event even if the click occurs with a keyboard.

For this reason, jQuery's click event will fire even if the checkbox is clicked by using the keyboard's spacebar. change, obviously, will fire every time the checkbox's state changes.

The checkbox just happens to be the special case where change and click are interchangable, because you can't fire the change event without also triggering click.

Of course, the exception to this rule is if you were to use javascript to manually alter the checkbox, such as:

/* this would check the checkbox without firing either 'change' or 'click' */ $('#someCheckbox').prop('checked',true);  /* this would fire 'change', but not 'click'. Note, however, that this    does not change the checkbox, as 'change()' is only the function that    is fired when the checkbox changes, it is not the function that    does the changing  */ $('#someCheckbox').trigger('change');  /* this would fire 'click', which by default change state of checkbox and automatically triggers 'change' */ $('#someCheckbox').trigger('click'); 

Here's a demonstration of these different actions: http://jsfiddle.net/jackwanders/MPTxk/1/

Hope this helps.

like image 118
jackwanders Avatar answered Sep 25 '22 05:09

jackwanders