Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery .change() not fire on radio buttons deselected as a result of a namesake being selected?

If I have several radio buttons of the same name, only one can be selected at any one time. When one becomes selected, any namesakes lose their selection. I'm intrigued as to why this doesn't constitute a .change() event for jQuery.

Hacking the $.change() function would be pretty drastic, but this doesn't seem to be reported as a bug — so I'm interested in finding out why this isn't the case.

Test below: I'd expect the two change events to fire whenever a radio is selected, but that isn't the case.

Here is the example: http://jsfiddle.net/XzmmW/

like image 837
Barney Avatar asked Jul 18 '11 17:07

Barney


People also ask

Can radio buttons be deselected?

It is important to know that a group of radio buttons cannot be deselected once selected. However, you can add an additional event to any event group and call it e.g. "none of the above" so that participants will be able to click on an alternative option if they do not want to choose any of the other options.

How to change radio button value in jQuery?

To select the value of the radio button we can set the “checked” to set to the desired option. For setting the property, we can use the prop() method in jQuery. Syntax: $(selector).


2 Answers

If you think of a set of radio buttons like a select element, it becomes clear why it's unnecessary to fire a change event for the deselected radio button.

When you change the selected option in a select element, you get one change event (you wouldn't expect anything else), rather than one for the previously selected option, and another for the newly selected option.

As has already been mentioned, when one radio button is selected, no others in the same set can be, so it would be redundant to fire a second change event.

Also note that this is not specific to jQuery - the standard JavaScript change event works in exactly the same way.

like image 115
James Allardice Avatar answered Oct 01 '22 17:10

James Allardice


There is only 1 change event... you changed from "old selection" to "new selection".

Keep in mind that although you have multiple "elements" they are all part of the same form element (as defined by the name attribute).

like image 37
scunliffe Avatar answered Oct 01 '22 17:10

scunliffe