Explain Codes LogoExplain Codes Logo

How to select a radio button by default?

html
radio-button
form-accessibility
angular
Alex KataevbyAlex Kataev·Aug 13, 2024
TLDR

To default-select a radio button, just add the checked attribute:

<input type="radio" name="group" value="A"> <input type="radio" name="group" value="B" checked> <!-- This 'checked' attribute is your magic wand --> <input type="radio" name="group" value="C">

"B" is now pre-selected. Change checked to another <input> to shuffle the default.

Let's dive into default selection

How 'checked' works

The checked attribute tells your browser to flag a radio button. It doesn't require a boolean (true or false); its sheer presence is enough.

HTML vs. XHTML

In XHTML, use checked="checked". Conversely, in standard HTML, the lonely checked makes your code both neat and compliant.

Angular's spin

If you're immersed in the Angular world, remember that ng-model binds the default-selected radio button in AngularJS. Angular 2+ uses [(ngModel)] to serve the same purpose.

Grouping and prioritizing for better readability

Name attribute for radio grouping

Use the same name for all radio buttons that belong to a single set to let the browser understand they belong to a single course menu.

Prioritizing highlighted attributes

Readable code is maintainable code. Therefore, prioritize attributes like checked in your tags.

Craft cleaner and more accessible forms

Clean code = happy developers

Remember, code isn't just for machines, it's for the people who maintain it. Keep it clean and efficient, and future you will thank you.

Make it adaptive

Screen readers and assistive technologies rely on proper implementation of the checked attribute to help end users navigate and use your forms effectively.

Angular's efficiency

Use [checked]="condition" or [value]="expression" in Angular forms for reactive and dynamic default selection handling.