Radio Button in HTML

Radio buttons are generally used in radio groups ( collection of radio buttons ) which is the set of related options. Only one radio button can be selected.
Let us have a look at an example.

Select a your favorite movie:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        Select a your favorite movie:
        <div>
            <input type="radio" id="f_g" name="movie" value="forest_gump">
            <label for="f_g">Forest Gump</label>
        </div>
        <div>
            <input type="radio" name="movie" id="s_r" name="movie" value="shawshank_red">
            <label for="s_r">Shawshank Redemption</label>
        </div>
        <div>
            <input type="radio" name="movie" id="s_l" name="movie" value="schindler_list">
            <label for="s_l">Schindler's List</label>
        </div>
    </body>
</html>
                        

In the above example, every radio button has the same name attribute which creates a radio group. We will discuss radio group in an upcoming section.

Attributes

Following attributes can be used while using radio button.

name attribute

name attribute is used to define radio group.
In a radio group, only on radio button can be selected.
A radio group can be created by assigning the single value to name attribute. In a radio group, when you select a radio button, the previously selected radio button will be deselected.
In the above example, so every radio button which has name = "movie" will be in a radio group. So only on radio button will be selected.
Another use of name attribute is to send the data to a server when you submit the form.
In the above example, when you select "Forest Gump" radio button and submit the form, then the data movie="forest_gump" will be sent to a server.

value attribute

value is assigned a string which will not be shown in browser but it will be sent to server with the name of the radio button. The value will only be sent to the server if a radio button is selected.
In the above example, when you select "Forest Gump" radio button and submit the form, then the data movie=forest_gump will be sent to a server.

checked attribute

checked attribute is added to make the radio button checked default.

for attribute

for attribute is not used in radio button but in the attached label. Value of the for is the id of the radio button. So that when you click on the label associated radio button gets checked/unchecked. It increases the hit area of the radio button.

Conclusion

In this section, we have learned about the radio button.
In next section, we will learn about select boxes in HTML.