I have a model Document which has attributes kind and context. Kind is an integer that's used as as enum (using the excellent active_enum
gem). Context only applies to documents of kind '2', i.e. if a document is any kind other than 2, context will be blank.
So in the form page to create a new Document, I have a <select>
to choose the kind, and a textarea for the context, which is initially hidden:
<%= form_for @document do |f| %>
...
<%= f.text_area :context, placeholder: 'Context', style: 'display:none' %>
<%= f.select :kind, Document.active_enum_for(:kind).to_select %>
...
<% end %>
And the textarea is shown and hidden using jQuery's show() and hide() methods in a function that's bound to the change() event on the dropdown.
So far, so good. But on the edit page for documents, I don't want the context textarea to always be hidden on the initial page load, because we may be editing a document of kind 2. So I want the textarea to initially be shown if we're editing a document of kind 2, but hidden in other cases.
Here's what I have now:
<% if @document.kind == 2 %>
<%= f.text_area :context, placeholder: 'Context' %>
<% else %>
<%= f.text_area :context, placeholder: 'Context', style: 'display:none' %>
<% end %>
Is there not a better way of doing this? This feels a bit wordy and redundant to me; is there no way I can just have one call to f.text_area
and include the style:
option conditionally?
Or am I overthinking this?
Use this :
<%= f.text_area :context, placeholder: 'Context', style: "#{'display:none' if @document.kind == 2}" %>
or you can add a css class for this,
display-none{
display:none;
}
<%= f.text_area :context, placeholder: 'Context', class: "#{'display-none' if @document.kind == 2}" %>
Thanks
or you can try javascript ? it's a way to reduce the duplicate code, if you have many fields to hide, this way has some advantages.
<%= f.text_area :context, placeholder: 'Context' %>
<script type="text/javascript">
$(function(){
if ($('#document_kind').val() != '2')
$('#document_context').hide();
});
</script>
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