Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
361 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...