I want to give a text_field class on a condition. Is there a way to do it in rails?
I.e.
<%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;', :class => 'required' %>
I need the class to be "required" only if a certain, condition occurs.
Use ternary (condition ? then : else
) operator:
<%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;',
:class => (condition ? 'required': '') %>
It's not easy to read, but solves your problem. Alternatively you can set a variable to the requred class name before using it in the link:
<% class = 'required' if condition %>
<%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;',
:class => class %>
In general in rails you can do something like
<% if condition %>
<%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;', :class => 'required' %>
<% else %>
<%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;' %>
<% end %>
Still your case is a bit more simple so you can do the check in place:
<%= text_field 'person', 'employer', :tabindex => 5,:style => 'width: 50%;', :class => condition ? 'required' : nil %>
This will result in class being nil if condition is not met and 'required' otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With