在带有数组的simple_form中禁用了单选按钮

时间:2013-08-26 11:31:29

标签: ruby-on-rails ruby ruby-on-rails-3 simple-form

在simple_form中放置两个单选按钮的最佳方法是什么? 默认情况下,一个按钮被禁用,另一个按钮被选中!

f.input_field :listing_type, as: :radio_buttons, collection: [ "lease", "sale"], :item_wrapper_class => 'inline'

这给了我两个按钮,其中两个按钮都被启用和选中。我希望销售被禁用,并且默认选择租约。

6 个答案:

答案 0 :(得分:3)

然后,您必须使用相同的名称单独创建它们,以便可以禁用其中一个。

<%= f.input :listing_type,     as: :radio_buttons, :disabled: true, input_html: { value: 'lease' } %>
<%= f.input :listing_type,     as: :radio_buttons, input_html: { value: 'sale' } %>

答案 1 :(得分:1)

这是更新的答案。您可以:

  • 通过将哈希添加到集合中来指定禁用哪个单选按钮:collection: [['op1', 'val1', disabled: false], ['op2', 'val2', disabled: true]]
  • 指定要选中哪个单选按钮,方法是将选中的添加到其集合哈希中,或者将checked: value_to_be_checked添加到主选项哈希中。 这是两个选项的示例:

example1:

<%= f.input_field :listing_type, as: :radio_buttons, collection: [ ['lease', 'lease', disabled: false], ['sale', 'sale', disabled: true]], checked: 'lease', :item_wrapper_class => 'inline' %>

example2:

<%= f.input_field :listing_type, as: :radio_buttons, collection: [ ['lease', 'lease', disabled: false, checked: true], ['sale', 'sale', disabled: true]], :item_wrapper_class => 'inline' %>

答案 2 :(得分:0)

试试这个

f.input_field :listing_type, as: :radio_buttons, collection: [ "lease", "sale"], :item_wrapper_class => 'inline', :checked => "lease"

答案 3 :(得分:0)

你可以通过jquery 坚持分离单选按钮来破解radio_button禁用的功能。

f.input_field :listing_type, as: :radio_buttons, collection: [ "lease", "sale"], :item_wrapper_class => 'inline', :checked=> "lease", :disabled=> true

<强> /app/assets/application.js

$(':radio:not(:checked)').attr('disabled', true);

答案 4 :(得分:0)

就我所知,单选按钮的行为与选择选项相同。如果您将数组传递给input的{​​{1}}选项,该选项包含显示文本,输入值以及任何其他HTML属性 - 按此顺序 - 您可以在单选按钮(或任何输入)中嵌入你想要的任何内容。

例如:

collection

这里我以HTML5禁用属性为条件。它在生成的HTML中完美地运行。

radio_button_options = LeaseCalculator::TERMS.map do |term|
  ["#{term} Months",term, {disabled: (term > maximum_term_length)}]
end

= form.input :term,
    as: :radio,
    collection: radio_button_options

注意:第二个输入上有HTML5禁用,第一个输入没有。

答案 5 :(得分:-1)

看到您可以使用form帮助器制作表单并设置默认值

 <% form_tag desired_path do %>
 <%= radio_button_tag(:options, "res_a", true) %>
 <%= label_tag "res a" %>
 <%= radio_button_tag(:options, "res_b") %>
 <%= label_tag "res_b" %>
 <%= submit_tag :value => "submit"%>
 <% end %>

通过提供true,您可以将选项设为默认选项。