views:

494

answers:

3

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.

+2  A: 

You need to give the two radio buttons the same name (so that they're in the same group), but different ids (so that you can associate the label with each one individually). I'm not familiar with ASP.NET MVC, so I don't know how to actually accomplish this, but that's the solution.

Edit: a second possibility is to wrap the radio buttons inside the label tag, like so:

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

* Note that this way may actually have better browser compatibility, I know some browsers are still iffy about the name/id distinction

Chad Birch
Im afraid this solution produces invalid html where id is dublicated
Claus Thomsen
It very well may. As I said, I don't know anything about ASP.NET MVC, I have no idea whether that first argument defines the id or the name attribute.
Chad Birch
Defines both the id and the name.
Graphain
+2  A: 

I'm not an asp programmer, so sorry if i'll tell something off :P

Label's attribute for is referenced to input's id. So you will have to do something like

<input type="radio" name="rad1" id="rad1_1"><label for="rad1_1">Rad1</label>
<input type="radio" name="rad1" id="rad1_2"><label for="rad1_2">Rad2</label>
Alekc
+7  A: 

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.

troethom