user4120314
user4120314

Reputation:

Show/hide form fields based on a selection from a drop down menu

I have this code but problem is that when the value is blank (option 1) states are shown up. How to hide it if the value is blank?

<select id="country"">
    <option value="" disabled="disabled" selected="selected">PLEASE CHOOSE</option>
    <option value="USA">USA</option>
    <option value="UK">UK</option>
    <option value="IT">ITALY</option>
</select>
<div id="states">
</div>

    $(document).ready(function(){
    $('#country').on('change', function() {
      if ( this.value == 'USA')
      {
        $("#states").show();
      }     
        else
      {
        $("#states").hide();
     }
    });
});

Upvotes: 1

Views: 18844

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388446

You can trigger the change event after the adding the handler. A namespaced event handler is used since we don't want any other handler to get executed.

$(document).ready(function() {
  $('#country').on('change.states', function() {
    $("#states").toggle($(this).val() == 'USA');
  }).trigger('change.states');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="country">
  <option value="" disabled="disabled" selected="selected">PLEASE CHOOSE</option>
  <option value="USA">USA</option>
  <option value="UK">UK</option>
  <option value="IT">ITALY</option>
</select>
<div id="states">states</div>

Upvotes: 7

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

Just trigger change :

$('#country').on('change', function() {
  if ( this.value == 'USA')
    $("#states").show();     
  else
    $("#states").hide();
}).trigger("change"); // notice this line

Upvotes: 2

Related Questions