capdiz
capdiz

Reputation: 101

Change controls depending on selected dropdown selected item in rails

I wonder if anyone could help with a code sample of what am trying to accomplish. I have a drop down select item in rails with to types of orders, an office order and home order. if a user selects home order in drop-down menu the text_field and text_area controls below it should change to this.

<%= f.text_field :home_address %>
<%= f.text_area :directions %>

and if they choose office order the controls should change to this

<%= f,text_field :office_address %>
<%= f.text_area :office_directions %>

I understand i should use ajax but an example would be helpful

EDIT


This is what i have. And its a rails view partial.

<%= form_for(@order) %> 
<select class="select">
  <option value="home">Home</option>
  <option value="office">Office</option>
</select>

<div id="home_address" style="display:none;">
   <%= f.text_field :home_address %>
   <%= f.text_area :directions %>
</div>

<div id="office_address" style="display:none;">
   <%= f,text_field :office_address %>
   <%= f.text_area :office_directions %>
</div>
<% end %>

<script type="text/javascript">
    $(document).ready(function() {
        $( ".select" ).change(function() {
            if(this.val() == 'office') {
            $('#office_address').show();
            } else {
            $('#home_address').show();
            }
        });
        });
</script>

Upvotes: 0

Views: 1298

Answers (1)

Debadatt
Debadatt

Reputation: 6015

You can put these two pairs of text_field and text_area with one portion in hidden

like

<div id="home_address" style="display:none">
<%= f.text_field :home_address %>
<%= f.text_area :directions %>
<div>
<div id="office_address" style="display:none">
<%= f.text_field :office_address %>
<%= f.text_area :office_directions %>
</div>

for script

$( ".select" ).change(function() {
 if($(this).val() == 'office') {
   $('#home_address').hide();
   $('#office_address').show();
 } else {
   $('#office_address').hide();
   $('#home_address').show();
 }
});

EDIT


<%= form_for(@order) do |f| %> 
<select class="select_option">
  <option value="home">Home</option>
  <option value="office">Office</option>
</select>

<div id="home_fields" style="display:none;">
   <%= f.text_field :home_address %>
   <%= f.text_area :directions %>
</div>

<div id="office_fields" style="display:none;">
   <%= f.text_field :office_address %>
   <%= f.text_area :office_directions %>
</div>
<% end %>

<script type="text/javascript">
    $(document).ready(function() {
        $( ".select_option" ).change(function() {
            if($(this).val() == 'office') {
              $('#home_fields').hide();
              $('#office_fields').show();
            } else {
              $('#office_fields').hide();
              $('#home_fields').show();
            }
        });
        });
</script>

Upvotes: 1

Related Questions