How to check a radio button with jQuery?
To programmatically select (check) a radio button using jQuery, the best practice is to use the .prop()
method:
$('input[name="myRadio"][value="option2"]').prop('checked', true);
Why .prop()
?
.prop('checked', true)
reflects the actual DOM property..attr('checked', 'checked')
modifies the HTML attribute, which isn’t always in sync with the current state if the user has interacted with the element.
Common Use Cases
- Setting a default selection after page load or a user action.
- Updating selected radio based on an API response or a condition in your script.
Unchecking a Radio Button
If you need to deselect a radio button, just set .prop('checked', false)
:
$('input[name="myRadio"][value="option2"]').prop('checked', false);
But remember, in a group of radio buttons, one is typically selected at any time. Unchecking one might need you to check another.
Level Up Your JavaScript Skills
Beyond quick jQuery tasks, a strong grasp of JavaScript fundamentals is crucial for building maintainable and efficient web apps. Consider:
-
Grokking JavaScript Fundamentals
Dive into the building blocks of JavaScript, from variables and scope to async operations. -
Grokking the Coding Interview: Patterns for Coding Questions
Learn problem-solving patterns commonly tested at FAANG and other top tech companies.
And for a real interview simulation, Coding Mock Interviews at DesignGurus.io connects you with ex-FAANG engineers to get personalized feedback on your coding approach and interview skills.
In short, just target the specific radio button by its name and value, then use .prop('checked', true)
to select it programmatically. This approach ensures the radio state is updated consistently and reliably in the DOM.