基于变量输出的单选按钮默认选中值 [英] radio button default checked value based on variable output
问题描述
我坚持要完成这项工作.我有一个数组 @names = ['abc', 'bbc', 'xyz']
我正在为它构建单选按钮,如下所示.
I am stuck to make this work. I have an array @names = ['abc', 'bbc', 'xyz']
for which I am building the radio button as follows.
<% @names.each do |n| %>
<%= f.radio_button :name, n, :checked => "checked" %>
<%= f.label :name, n.capitalize %>
<% end %>
我有另一个变量 @select = 'bbc'
它包含必须在上述单选按钮中选择的字符串.目前,最后一个单选按钮正在接受检查,即 'xyz'
.如何实现这一目标.请帮忙.
I have another variable @select = 'bbc'
which contains the string which has to be selected among the above radio buttons. Currently the last radio button is getting check i.e, 'xyz'
. How to achieve this. Please help.
推荐答案
您的代码实际上是将 checked="checked"
属性设置为每个单选输入,这没有意义,因为单选按钮是多个选项中的一个答案.
Your code is actually setting the attribute checked="checked"
to every radio input, which does not make sense since Radio Buttons are there for a single answer among multiple choices.
添加一个小测试以仅检查一个单选按钮:
Add a small test to check only one radio button:
<% @names.each do |n| %>
<%= f.radio_button :name, n, :checked => n == @select %>
<%= f.label :confidentiality_level, n.capitalize %>
<% end %>
长版:
<% @names.each do |n| %>
<% if @select == n # tests if n is equal to 'xyz' or whatever %>
<%= f.radio_button :name, n, :checked => "checked" %>
<% else %>
<%= f.radio_button :name, n %>
<% end %>
<%= f.label :confidentiality_level, n.capitalize %>
<% end %>
这篇关于基于变量输出的单选按钮默认选中值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!