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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With