Sam Hakim
Sam Hakim

Reputation: 69

Conditionally show fields on Ruby on Rails form

I have a Ruby on Rails app using Bootstrap for styling. This is a snippet from a form and I want to make a field visible once the non-blank value from the previous field is selected. Thus, once non-blank 'criteria' is selected, I want to make the 'criteria_reason' field visible. How can this code be fixed?

<%= f.select :criteria, ['', 'Yes', 'No', 'Maybe'] %>

<%= f.text_field :criteria_reason, class:"form-control", placeholder:'Reason',
      style:"#{'display:none' if :criteria == ''}" %>

Thanks!

Upvotes: 1

Views: 3137

Answers (2)

akbarbin
akbarbin

Reputation: 5105

you can use javascript to make it visible on invisible when you click drop-down.

<script type="text/javascript">
  $(function () {
    $("#category_category_id").change(function () {
        var category = $(this).val();
        if (category != "") {
          $("#category_criteria_reason").show();
        } else {
          $("#category_criteria_reason").hide();
        }
    });

  });
</script>

change category_ with you own form class. Then, you can change you default code into

<%= f.text_field :criteria_reason, class:"form-control", placeholder:'Reason',
      style:"#{'display:none' if f.object.criteria == ''}" %>

Upvotes: 4

Tim Kretschmer
Tim Kretschmer

Reputation: 2280

by calling form_for @object do |f| you are passing @object into a ActionView::FormBuilder. In f you can access the related object by calling f.object

so in this case you need to do

<%= f.text_field :criteria_reason, class:"form-control", placeholder:'Reason',
      style:"#{'display:none' if f.object.criteria == ''}" %>

see http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html

Upvotes: 2

Related Questions