Ilya I
Ilya I

Reputation: 1282

How to get Bootstrap button-like checkbox initially checked?

I have a problem with the following code in the view:

<div class="btn-group" data-toggle="buttons">
  <%= f.label :private, class: "btn btn-default" do %>
    <%= f.check_box :private %> Private
  <% end %>
</div>

Technically it works, but when the private field is initially true (i.e. checked) the button looks as if it was unchecked. Perhaps it is due the fact that check_box helper generates two inputs, one of which is hidden.

Could someone show an example implementation of Bootstrap checkboxes in the Rails view?

Upvotes: 3

Views: 5547

Answers (2)

Ilya I
Ilya I

Reputation: 1282

It turned out that Bootstrap scripts just do not update the state on page load. So I solved it with this JavaScript code snippet:

$("[data-toggle='buttons'] .btn").each(function(i, el) {
  var $button = $(el);
  var checked = $button.find("input[type='checkbox']").prop("checked");
  if (checked) {
    $button.addClass("active");
  } else {
    $button.removeClass("active");
  }
});

Upvotes: 2

Undistraction
Undistraction

Reputation: 43341

Here is a working checkbox from one of my projects generated using Simple Form:

<%= f.input :cost, label: "Cost to access resource" %>

Which generates:

<div class="form-group boolean optional archive_resource_cost">
   <input name="archive_resource[cost]" type="hidden" value="0" />
   <label class="boolean optional checkbox" for="archive_resource_cost">
   <input checked="checked" class="boolean optional" id="archive_resource_cost" name="archive_resource[cost]" type="checkbox" value="1" />
      Cost to access resource
   </label>
</div>

Is your :private model attribute definitely boolean?

Upvotes: 0

Related Questions