4

I have the following button in my view:

<button type="button" class="btn btn-lg btn-primary">Primary button</button>

I want to add the disabled property to it if and only a certain condition is true. How do I this in an elegant way?

user1175969
  • 540
  • 6
  • 19

4 Answers4

9

You could use the rails helper button_tag with a boolean check

<%= button_tag "Primary button", class: 'btn btn-lg btn-primary', 
  disabled: condition_check_method %>
Ropeney
  • 1,065
  • 8
  • 10
2

You Should do this two or more way:

<button type="button" class="your-class btn btn-lg btn-primary">Primary button</button>

<script type="text/javascript">
  $(function(){
    if(Condition){
      $('.your-class').addClass('disabled');
    }
  });
</script>

OR
In The rails term 

<button type="button" class="btn btn-lg btn-primary <%= conditon ? "disabled" : ""%>">Primary button</button>
Kaushlendra Tomar
  • 1,410
  • 10
  • 16
2

@Ropeney's way is the RoR way, but here's another solution:

<% #some condition %>
<% foo == bar ? ( disabled = "disabled") : (disabled = "") %>

<!-- insert "disabled" or "" (empty string) in the markup -->
<button type="button" class="btn btn-lg btn-primary" <%= disabled %> >Primary button</button>

Note: we can use only disabled in HTML5 - Correct value for disabled attribute

Community
  • 1
  • 1
Vucko
  • 20,555
  • 10
  • 56
  • 107
0

I think this may work for you

<button type="button" class="btn btn-lg btn-primary" disabled="<%= @check_condition ? 'disabled' : '' %>">Primary button</button>

or

<button type="button" class="btn btn-lg btn-primary" <%= @check_condition ? 'disabled' : '' %>">Primary button</button>
Kinjal Shah
  • 577
  • 1
  • 5
  • 15