Radio buttons are a common form element used to allow users to select one option from a group of options. In many cases, you may want to have one of the radio buttons selected by default when the page loads. This can be useful for providing a default choice or guiding the user’s selection.
To set a default radio button, you can use the checked
attribute in HTML. The checked
attribute is a boolean attribute that specifies whether the radio button should be checked by default.
Here’s an example of how to use the checked
attribute:
<input type="radio" name="imgsel" value="" checked>
In this example, the radio button with the name "imgsel" and an empty value will be selected by default when the page loads.
It’s worth noting that the actual value of the checked
attribute does not matter. The presence of the attribute itself is what determines whether the radio button should be checked or not. This means you can use either checked="checked"
or simply checked
, and both will achieve the same result.
If you’re using a JavaScript framework like AngularJS, the approach may be slightly different. In AngularJS, you can bind the radio buttons to a model using the ng-model
directive, and then set the default value in your controller.
For example:
<input type='radio' name='group' ng-model='mValue' value='first'>First
<input type='radio' name='group' ng-model='mValue' value='second'> Second
In your controller, you can set the default value like this:
$scope.mValue = "second";
This will select the second radio button by default when the page loads.
It’s also important to note that in AngularJS 2.x and above, the ng-checked
attribute should be used instead of the checked
attribute.
In summary, setting a default radio button is a simple process that involves adding the checked
attribute to the desired radio button. Whether you’re using plain HTML or a JavaScript framework like AngularJS, this technique can help guide the user’s selection and provide a better user experience.