How to hide part of a rails 3 form depending on value selected from dropdown menu

forms, ruby-on-rails, ruby-on-rails-3

Solution

For this you need some JavaScript. Use an `onchange` event handler to monitor the `<select>` input for changes. Compare the input value and conditionally set/unset a `disabled` attribute on the `#project_capital_cost` input. You can use jQuery for this.

By default, Rails 3 enables jQuery by including the `jquery_rails` gem in your Gemfile. Assuming you have `jquery_rails` included in your app and your `<select>` and `<input>` tags have `#project_status` and `#project_capital_cost` IDs respectively, add the following script into your `_form` partial with necessary modification:

<script>
  $(document).ready(function(){
     if($('#project_status').val() != "In Progress"){
        $("#project_capital_cost").attr('disabled','disabled');
     }
     else{
        $("#project_capital_cost").removeAttr('disabled');
     }

     $('#project_status').change(function(){
        if($(this).val() != "In Progress"){
          $("#project_capital_cost").attr('disabled','disabled');
        }
        else{
          $("#project_capital_cost").removeAttr('disabled');
        }
     })
  });

</script>

EDIT:

To hide `div` give some `id` to it:

  <div class="field" id="my_div">
    <%= f.label "Capital Cost" %><br />
    <%= f.text_field :capital_cost %>
  </div>

Then replace

`$("#project_capital_cost").attr('disabled','disabled');` with `$("#my_div").css('display','none')`

and

`$("#project_capital_cost").removeAttr('disabled');` with `$("#my_div").css('display','block')` in script.

Problem

I have a a partial, _form for one of my views in rails. It looks like so: ``` <%= form_for(@project) do |f| %> <div class="field"> <%= f.label "Project Status" %><br /> <%= f.select :status, ["In Progress", "Cancelled"] %> </div> <div class="field"> <%= f.label "Capital Cost" %><br /> <%= f.text_field :capital_cost %> </div> <div class="actions"> <%= f.submit %> </div> <% end %> ``` I'd like the "capital cost" part of the form to be greyed out unless "In Progress" is selected from the dropdown menu, without having to reload the page. Is this possible? I saw some solutions using javascript, but I'm a complete beginner and couldn't get my head around them (unfortunately I don't have the time to learn to use js before I have to finish this project). Cheers!

Original source