How to hide part of the form of rails 3 depending on the value selected from the drop-down menu

I have a partial, _form for one of my views in rails. It looks like this:

<%= 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 would like to see some of the "capital expenditures" in the form grayed out if "Running" is not selected in the drop-down menu, without having to reload the page. Is it possible? I saw some solutions using javascript, but I am a complete beginner and could not make out them (unfortunately, I do not have time to learn to use js before I have to finish this project). Hooray!

+5
source share
2 answers

JavaScript. onchange <select> . / disabled #project_capital_cost. jQuery .

Rails 3 jQuery, jquery_rails gem Gemfile. , jquery_rails, , <select> <input> #project_status #project_capital_cost , script _form :

<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:

div, id:

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

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

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

+6

, HTML- .

<input disabled="disabled">

Rails

<%= f.text_field :capital_cost, :disabled => "disabled", :id => "capital_cost_input" %>

, "", AJAX Javascript, Rails.

<%= f.select :status, ["In Progress", "Cancelled"],
             {},
             "data-remote" => true, "data-url" => ..._path %>

onchange AJAX.

AJAX URL- "URL- ".

AJAX Javascript . -

$('#capital_cost_input').removeAttr("disabled")
+3

All Articles