In this article, we will introduce a method to add multiple groups of radio buttons in one form in HTML.
Use the Different Value for the
name Attribute for Different Groups of Radio Button in HTML
While working with radio buttons in HTML, sometimes you might need to use multiple groups of radio buttons in a single form. In such a case, selecting a group’s radio button may deselect the other group’s radio button.
To eliminate this problem, the value of the
name attribute in the button element of the two groups must be different. It means that for the first group of radio buttons, we should use the same value for the
name attribute in all of the radio buttons.
For the second group, the value of the
name attribute should be different from the first group, but all the radio buttons in the second group should have the same value.
We can also use the
fieldset element to separate the two groups visually. The
<fieldset> tag groups the related elements in HTML.
In the example below, we will create two groups of radio buttons. In the first group, the user will be able to select a motorcycle, and in the second group, they will be able to select a car.
For example, create a form using the
<form> tag. Then, use the
<fieldset> tag for the group of motorcycle radio buttons.
Create a radio button for
Honda and set the value
motorcycle for the
name attribute. Next, create another radio button for
Yamaha and again set the value of the
name attribute to
After closing the
<fieldset> tag, create another
fieldset element for car radio buttons. In the car, create radio buttons for
name attribute’s value to
car for both the buttons. The code example is shown below.
<form> Select a Motorcyle <fieldset id="motorcyle"> <input type="radio" value="Honda" name="motorcycle"> <label for="Honda">Honda</label><br> <input type="radio" value="Yamaha" name="motorcycle"> <label for="Yamaha">Yamaha</label><br> </fieldset><br> Select a Car <fieldset id="car"> <input type="radio" value="Hyundai" name="car"> <label for="hyundai">Hyundai</label><br> <input type="radio" value="Toyota" name="car"> <label for="toyota">Toyota</label><br> </fieldset> </form>
Thus, we can select each motorcycle and car from the two groups of a radio button. The
fieldset element creates a border around each group.
This way, we can add two groups of radio buttons in a single form in HTML.