Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Toggle Buttons in place of Check boxes (Rails, Twitter Bootstrap, Simple_form)

I am using Simple_form, twitter bootstrap, and rails 3.2.2

Does anyone know if there is a way to use the "toggle button" option for bootstrap on boolean fields in a simple_form? I would like to replace the checkboxes with buttons.

Here is what I've tried so far in the form (rails):

<%= f.input :client_approved, :input_html => { :class => 'btn btn-primary', :data => {:toggle => 'button'} } %>

Here is the HTML output:

<input class="boolean optional btn btn-primary" data-toggle="button" id="id_card_design_client_approved" name="id_card_design[client_approved]" type="checkbox" value="1">

Any ideas on how to assign a button tag to the simple_form input?

like image 618
prodigerati Avatar asked Apr 14 '12 20:04

prodigerati


1 Answers

I've come up with a JS based approach... I'm sure it's not the nicest way of doing it, but it works...

In your view file, add something along the lines of this:

<div id="client_approved_buttons" class="btn-group" data-toggle="buttons-radio">
  <%= f.input : client_approved, as: :hidden %>
  <a class="btn" data-value="1">Yes</a>
  <a class="btn" data-value="0">No</a>
</div>

Then in your JS file, add this:

// make button toggles update hidden field
$('.btn-group a').on('click', function(event){
  event.preventDefault();
  var input = $(this).siblings('.control-group').find('input[type=hidden]');
  if(input.length>0){
    if(input.val().toString() !== $(this).data('value').toString()){
      input.val($(this).data('value')).trigger('change');
    }
  }
});
like image 144
Jules Copeland Avatar answered Nov 08 '22 13:11

Jules Copeland