Jquery $("#radioButton").change(...) not firing during de-selection
The de-selection of a radio button doesn't trigger a change
event in jQuery as the event is designed to catch selections. So, the strategy is to monitor changes on the entire group of radio buttons.
Check out this neat piece of code for identifying selections:
This ties the change
event to every radio button in the group (those sharing the same name
), catching any shuffles in the selections and helping to identify which button is on duty (i.e., checked).
Calling Dynamic Elements to Order
In case of dynamically added elements (those that sneak in after the page load), direct binding of events won't work. Here, you need to call in the power of event delegation:
This technique involves appointing a common parent element, surprisingly often the document itself, to keep an eye on the radio buttons added after the initial bell rings (page loads).
Toggling Elements: Enabled and Disabled
When it comes to enabling or disabling elements based on the radio button's current mood (state), always call prop()
to duty.
To show the red card (disable an element), set the disabled
attribute to true
.
The Right Attribute at the Right Time
Choosing the correct function between prop()
and attr()
can save a lot of head scratching.
Here's a pro tip:
prop()
handles properties that change over time like,checked
,disabled
, andselected
.attr()
refers to the true HTML attribute of an element, fundamentally immortal and unchanging post page load.
The Power of the :checked Selector
The mighty :checked
selector in jQuery is the superhero you need for quickly identifying the chosen radio button:
No riddles here, just straight-up, efficient solutions when you're running logic based on the current state.
Managing Change in Groups
Say you have a group of radio buttons and each one when selected should unlock a unique superpower (perform a unique action). We've got you covered:
Each condition checks the state of a specific radio button, dividing the actions as clearly as water and oil.
Dealing with the De-selection Dilemma
To deal with the dilemma of de-selection, we make de-selection into action:
Remember, in the game of radio buttons, when one button wins (gets selected), another loses (gets de-selected). And we can use that to our advantage.
Was this article helpful?