Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to associate labels with radio buttons

I'm using MVC, and I've got a simple radio button setup:

<%=Html.RadioButton("my_flag", True)%><label>Yes</label> <%=Html.RadioButton("my_flag", False)%><label>No</label> 

The only thing I'm missing is that you can't click the label to select the radio button. Normally you'd use:

<label for="my_flag"> 

but that associates both labels with the last radio button. Is there any way to associate the labels with the correct radio button?

Note: This is mimicking a paper form, so switching to a checkbox is not an option.

like image 875
gfrizzle Avatar asked Mar 18 '09 15:03

gfrizzle


People also ask

How do you style a radio button label?

Just use label:focus-within {} to style a label with a checked radio or checkbox. Show activity on this post. Show activity on this post. As TimStieffenhofer mentioned in their answer, the easiest way is to have the input field as a child of the label and use the :focus-within pseudo-class on the label.

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 I group radio buttons?

You group radio buttons by drawing them inside a container such as a Panel control, a GroupBox control, or a form. All radio buttons that are added directly to a form become one group. To add separate groups, you must place them inside panels or group boxes.


1 Answers

You have two different ways to implement this.

The first one is the simple solution is to embed the radio button inside a <label/> tag.

<p>     <label><%=Html.RadioButton("option", "yes") %> Yes</label> </p>  <p>     <label><%=Html.RadioButton("option", "no") %> No</label> </p> 

The second path is to associate each radio button with an ID. This is also quite simple with the htmlAttributes argument and it allows for more flexibility in regard to the form layout:

<p>     <label for="option_yes">Yes:</label>     <%=Html.RadioButton("option", "yes", new { id = "option_yes" }) %> </p>  <p>     <label for="option_no">Np:</label>     <%=Html.RadioButton("option", "no", new { id = "option_no" }) %> </p> 

I would recommend the latter, and it seems to be the one you are asking for too.

EDIT

In fact you should give the argument with the ID attribute no matter what. If you don't do this, your site will have multiple elements with the same ID, and this fails HTML validation.

like image 96
Troels Thomsen Avatar answered Sep 24 '22 03:09

Troels Thomsen