matiss
matiss

Reputation: 747

Rails 5: disable checkbox on condition

I'm trying to figure out how to make checkbox disabled on condition?

This is my piece of code from view:

<%= f.collection_check_boxes(:company_ids, @user_companies, :id, :name) do |b| %>
 <div class="col-sm-1">
   <%= b.check_box %>
 </div>
   <%= b.label %><br><br>
<% end %>

I need to make it disabled if @user = current_user

In collection_check_boxes docs I don't see how to accomplish this. I assume there is some way, but so far no luck of finding one. My naive thinking was maybe condition can be stated somehow in view. Answers here show how to do that with check_box_tag.

I'd be happy for any hint how to solve this. Thank you!

Upvotes: 6

Views: 8837

Answers (3)

ahuenchu
ahuenchu

Reputation: 1

You can use this to disable the checkbox, and show the div disable also.

<%= f.collection_check_boxes(:company_ids, @user_companies, :id, :name) do |b|%>
 <div class="col-sm-1 <%=(@user == current_user) ? "disabled​" : ""%>">
   <%= b.check_box( onclick:"return false;")) %>
  </div>
   <%= b.label %><br><br>
 <% end %>

Upvotes: 0

chad_
chad_

Reputation: 3819

If you just want to use the HTML disabled attribute, you could do something like this:

<%= f.collection_check_boxes(:company_ids, @user_companies, :id, :name) do |b| %>
  <div class="col-sm-1">
    <%= b.check_box disabled: @user == current_user  %>
  </div>
  <%= b.label %><br><br>
<% end %>

Upvotes: 9

Mayank
Mayank

Reputation: 727

Use bootstrap disabled class or create one with as

.disabled{
  pointer-events: none;
   cursor: not-allowed;
 }

Now you can use this class to disable the check box.

<%= f.collection_check_boxes(:company_ids, @user_companies, :id, :name) do |b| %>
 <div class="col-sm-1">
   <%= b.check_box( class: (@user == current_user) ? "disabled​" : "" ) %>
  </div>
   <%= b.label %><br><br>
 <% end %>

You can also use display property to hide element on basis of class of element

Hope this helps

Upvotes: 0

Related Questions