Search code examples
javascriptjqueryjquery-uiruby-on-rails-4simple-form

How to show hide a text field when something is selected from a drop down.


My question is, if I select something in my drop down like ABS when ABS is selected how can I have a text box show up for additional information to input. What I have now isn't working...Any help is much appreciated!

This is my app.js

$(document).ready(function(){

$('#indirect_id').change(function() {
    var indirect_id = $(this).val();
    if(indirect_id == 'ABS'){
      $('#sick_comment').show();
    }
    else{
      $('#sick_comment').hide();
    }
  });

This is my view

.row-fluid
  =simple_form_for @entry, :url => url_for(:controller => 'entry', :action => 'create'), :method => :post do |f|

%table.table.table-bordered.table-striped{:style => 'table-layout:fixed; width:100% !important;'}
  %th.lt Indirect Code:
  %td.lt= f.input_field :indirect_id, :as => :select, :label => false, :collection => ['PD', 'VAC', 'ABS'], :id => 'indirect_id', :input_html => {:value => ''}


  %th.lt Optional Comment
  %td.lt= f.text_field :sick_day,  :label => false, :id => 'sick_comment', :input_html => {:value => ''}

%table.table.table-bordered.table-striped{:style => 'table-layout:fixed; width:100% !important;'}
= f.button :submit, "Submit", :class => 'btn btn-primary', :style => 'margin-left:50px;'

Solution

  • If that is the full text of your app.js, then you are missing an end bracket and parenthesis:

     $(document).ready(function(){
        $('#indirect_id').change(function() {
            var indirect_id = $(this).val();
            if(indirect_id == 'ABS'){
              $('#sick_comment').show();
            }
            else{
              $('#sick_comment').hide();
            }
          });
        });