Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

html - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...