Explain Codes LogoExplain Codes Logo

Assign an initial value to radio button as checked

html
best-practices
responsive-design
form-design
Nikita BarsukovbyNikita Barsukov·Sep 20, 2024
TLDR

Assign the default checked status to a radio button by using the checked attribute:

<input type="radio" name="option" value="Option1" checked>An exciting option <input type="radio" name="option" value="Option2">A boring option

This ensures Option1 is pre-selected when the page loads.

Suiting every scenario

Using the checked attribute is straightforward. Still, it's beneficial to understand how it performance in various scenarios and how to employ best practices:

Dynamically updating with JavaScript

In scenarios where the checked status needs to be dynamic, JavaScript is a handy tool:

document.getElementById("option1").checked = true; // JavaScript, saving the day once again

This makes use of the id attribute assigned to a radio button:

<input type="radio" id="option1" name="option" value="Option1">An exciting option <input type="radio" name="option" value="Option2">A boring option

Prioritizing accessibility

Include a <label> element for every radio button to accommodate screen readers and accessible interfaces:

<label for="option1">An exciting option</label> <input type="radio" id="option1" name="option" value="Option1" checked> <label for="option2">A boring option</label> <input type="radio" id="option2" name="option" value="Option2">

Keeping your radio buttons in check

Ensure radio buttons within the same group share the same name attribute, so only one button can be selected at a time:

<!-- Keeping things in check --> <input type="radio" name="option" value="Option1" checked>An exciting option <input type="radio" name="option" value="Option2">A boring option

Employing frameworks

In frameworks like Angular, the checked attribute can be achieved like this:

<!-- Angular is LinkedIn, and checked="checked" is the endorsement --> <input type="radio" [checked]="choice == defaultChoice">

For React applications:

<!-- React - where JS and HTML had a baby --> <input type="radio" checked={this.state.choice === defaultChoice} onChange={this.handleChange} />

State management must be remembered when you're dealing with dynamic forms in modern web applications.

Beyond the initial scope

Handling form resets

JavaScript ensures the checked status reflects the default value if the form restarts:

formElement.reset(); // Kicking it old school

Enhancing user feedback

Stylish radio buttons enhance user interaction, and styled labels can provide visible feedback:

input[type="radio"]:checked + label { font-weight: bold; // Because who doesn't love a bold radio button? }

Checking browser compatibility

Test your implementation's behavior across different browsers and devices. Subtle changes can impact your UX.