Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "label for" on radio buttons

People also ask

How do I add a label to a button?

You can create it using a <label> element. You will need to bind the label to the input element by setting the for attribute on the label to the same value as the id attribute on the input element.

How do you label a group of radio buttons?

Radio buttons Radio button groups should always be grouped using <fieldset> .

What is the use of label option button?

Radio button allows user to choose only one of the pre-defined options. Each radio button must be accompanied by a label describing the choice it represents.


You almost got it. It should be this:

<input type="radio" name="group1" id="r1" value="1" />
<label for="r1"> button one</label>

The value in for should be the id of the element you are labeling.


Either structure is valid and accessible, but the for attribute should be equal to the id of the input element:

<input type="radio" ... id="r1" /><label for="r1">button text</label>

or

<label for="r1"><input type="radio" ... id="r1" />button text</label>

The for attribute is optional in the second version (label containing input), but IIRC there were some older browsers that didn't make the label text clickable unless you included it. The first version (label after input) is easier to style with CSS using the adjacent sibling selector +:

input[type="radio"]:checked+label {font-weight:bold;}

(Firstly read the other answers which has explained the for in the <label></label> tags. Well, both the tops answers are correct, but for my challenge, it was when you have several radio boxes, you should select for them a common name like name="r1" but with different ids id="r1_1" ... id="r1_2"

So this way the answer is more clear and removes the conflicts between name and ids as well.

You need different ids for different options of the radio box.

<input type="radio" name="r1" id="r1_1" />

       <label for="r1_1">button text one</label>
       <br/>
       <input type="radio" name="r1" id="r1_2" />

       <label for="r1_2">button text two</label>
       <br/>
       <input type="radio" name="r1" id="r1_3" />

       <label for="r1_3">button text three</label>