Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Best way to conditionally show/hide a form field?

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?

like image 751
GMA Avatar asked Aug 12 '13 08:08

GMA


Video Answer


2 Answers

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

like image 154
Rails Guy Avatar answered Sep 28 '22 09:09

Rails Guy


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>
like image 35
Bigxiang Avatar answered Sep 28 '22 09:09

Bigxiang