Rails 3 + 简单形式 + bootstrap Radio 和复选框作为带切换功能的按钮

Lui*_*luz 5 ruby-on-rails-3 simple-form twitter-bootstrap

我正在尝试让我的收音机和复选框用作具有切换功能的按钮,如 Twitter 引导页面上所示。关联

我以某种方式设法让这些按钮在数据库中显示和运行,但是当用户返回页面时,它们不会被切换。我想知道这是否可能。如果是,我如何在我的代码上实现它?我正在使用 simple_form + twitter bootstrap。

这是我用来显示单选按钮的代码:

<div class="btn-group" data-toggle="buttons-radio">
<%= f.input :child_gender, :label => "Child gender?", :collection => [['Boy', 'Boy'], ['Girl', 'Girl'], :as => :radio_buttons, :input_html => { :data => {:toggle => 'buttons-radio'} }, :item_wrapper_class => 'btn btn-toggle btn-small inline' %>
</div>
Run Code Online (Sandbox Code Playgroud)

这是复选框按钮的代码:

<div class="btn-group">
<%= f.input :child_size, :label => "What size?", :collection => child_size, :as => :check_boxes, :input_html => { :data => {:toggle => 'buttons-checkbox'} }, :item_wrapper_class => 'btn btn-toggle btn-small' %>
</div>
Run Code Online (Sandbox Code Playgroud)

这是我的自定义 CSS btn-toggle

.btn-toggle input {
    display: none;
}
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏。

nic*_*kl- 2

这是simple_form input我们缺少的引导单选按钮。

# lib/inputs/button_radio_input.rb
class ButtonRadioInput < SimpleForm::Inputs::CollectionRadioButtonsInput
  def input
    out = <<-HTML

<div class="btn-group" data-toggle="buttons-radio">
HTML
    input_field = @builder.hidden_field(attribute_name, input_html_options)
    input_id = input_field[/ id="(\w*)/, 1]
    label_method, value_method = detect_collection_methods
    collection.each {|item|
      value = item.send(value_method)
      label = item.send(label_method)
      on_click = "document.getElementById('#{input_id}').value='#{value}';return false;"
      active = ''
      active = ' active' unless
          out =~ / active/ ||
          input_html_options[:value] != value &&
          item != collection.last
      input_html_options[:value] = value unless active.empty?
      btn = 'btn'
      btn = "btn btn-#{item.third}" unless item.third.nil?
      out << <<-HTML
  <button onclick="javascript:#{on_click}" type="button" class="#{btn}#{active}">#{label}</button>
HTML
    }
    value = <<-VAL
value="#{input_html_options[:value]}"
VAL
    input_field[/value="[^"]*"/] = value.chomp if input_field =~ /value/
    input_field[/input/] = "input #{value.chomp}" unless input_field =~ /value/
    out << <<-HTML
  #{input_field}
</div>
HTML
    out.html_safe
  end
end
Run Code Online (Sandbox Code Playgroud)

它支持所有as: :radio_buttons可接受的内容,并为按钮样式添加了可选的第三个参数。

= f.input :rad_buttons,
  as: :button_radio,
  collection: [ [:blue, 1, :primary],
    [:red, 2, :danger],
    [:green, 3, :success],
  ]
Run Code Online (Sandbox Code Playgroud)

上面的 haml 片段将生成一个三个单选按钮组

  • 第一个按钮的样式btn-primary带有标签blue和值1
  • 第二个按钮的样式btn-danger带有标签red和值2
  • 第三个按钮的样式btn-success带有标签green和值3

由于我们没有分配值 ( input_html: {value: 1}),最后一个按钮将被激活(与普通单选按钮的行为相同),并且 的值rad_buttons将是3

欢乐!