我的问题类似于这个, 但对于Rails应用程序.
我有一个带有一些单选按钮的表单,并希望将标签与它们相关联.的label形式辅助只需表单字段作为参数,但在这种情况下,我有一个单一的表单字段多个单选按钮.我看到的唯一方法是手动创建标签,硬编码为单选按钮自动生成的ID.有谁知道更好的方法吗?
例如:
<% form_for(@message) do |f| %>
<%= label :contactmethod %>
<%= f.radio_button :contactmethod, 'email', :checked => true %> Email
<%= f.radio_button :contactmethod, 'sms' %> SMS
<% end %>
Run Code Online (Sandbox Code Playgroud)
这会产生类似于:
<label for="message_contactmethod">Contactmethod</label>
<input checked="checked" id="message_contactmethod_email" name="message[contactmethod]" value="email" type="radio"> Email
<input id="message_contactmethod_sms" name="message[contactmethod]" value="sms" type="radio"> SMS
Run Code Online (Sandbox Code Playgroud)
我想要的是:
<input checked="checked" id="message_contactmethod_email" name="message[contactmethod]" value="email" type="radio"><label for="message_contactmethod_email">Email</label>
<input id="message_contactmethod_sms" name="message[contactmethod]" value="sms" type="radio"> <label for="message_contactmethod_sms">SMS</label>
Run Code Online (Sandbox Code Playgroud) 我有这个单选按钮(和其他一些后):
<input type="radio" name="group1" value="Milk"> Milk<br>
Run Code Online (Sandbox Code Playgroud)
但是,如果我想激活单选按钮,我必须单击它,单击按钮右侧的"Milk"一词,不会激活它.我怎么能这样做呢?到目前为止我发现的关于单选按钮的所有例子都有同样的问题.提前致谢.
我有这个剃刀模板
<table>
<tr>
<td>@Html.RadioButtonFor(i => i.Value, "1")</td>
<td>@Html.LabelFor(i => i.Value, "true")</td>
</tr>
<tr>
<td>@Html.RadioButtonFor(i => i.Value, "0")</td>
<td>@Html.LabelFor(i => i.Value, "false")</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
这给了我这个HTML
<table>
<tr>
<td><input id="Items_1__Value" name="Items[1].Value" type="radio" value="1" /></td>
<td><label for="Items_1__Value">true</label></td>
</tr>
<tr>
<td><input checked="checked" id="Items_1__Value" name="Items[1].Value" type="radio" value="0" /></td>
<td><label for="Items_1__Value">false</label></td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
所以我有Items_1__Value两次ID - 当然 - 不好,当我点击第二个标签"false"时,在浏览器中不起作用,第一个收音机将被激活.
我知道我可以在RadioButtonFor中添加一个自己的Id并用我的标签来引用它,但这不是很好,是吗?特别是因为我处于一个循环中而且不能只使用带有附加数字的名称"value",这最终会在我的最终HTML标记中出现在多个Dom Ids中.
不应该是一个很好的解决方案吗?
我的表单中有一些选项按钮,我总是需要单击圆形选项按钮来选择它.有没有办法让用户点击相关标签来选择选项按钮?

<p>
<span class="editor-label">
@Html.LabelFor(m => m.ADR)
</span>
<span class="editor-field">
@Html.RadioButtonFor(model => model.ADR, "Yes", AdrYesOptions)
@UserResource.YesValue
@Html.RadioButtonFor(model => model.ADR, "No", AdrNoOptions)
@UserResource.NoValue
</span>
</p>
Run Code Online (Sandbox Code Playgroud)
我在这里找到了一些解决方案:如何将标签与单选按钮相关联但这些不适合我,因为我更喜欢MVC专用的解决方案.