Skip to content Skip to sidebar Skip to footer

How To Show/hide Divs With Multiple Select Options

I've been sorting a HTML5 form with jQuery to show/hide divs based on the selected value in the select menu. However I've come across a problem where if an option is selected, then

Solution 1:

You haven't actually included any code within your change function which will hide the divs. I guess that the intention of $('.not-selected').hide();was to do this but you never apply the .not-selected class to any of the country divs.

Perhaps a simple method would be to call the hide() function on all the country divs every time a change is made.

$(document).ready(function(){        
  $('.country_option').change(function() {
    $('.england, .scotland, .ireland, .wales').hide();
    $('#' + $(this).val()).show();
  });
});

Solution 2:

Your code should be looks like this

$(document).ready(function(){
  
$('.england, .scotland, .ireland, .wales').hide();
  $('.country_option').change(function() {
    $('.england, .scotland, .ireland, .wales').hide();
  $('.not-selected').hide();
  $('#' + $(this).val()).show();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="country">
  <h1>Pick country</h1>
  <select class="country_option">
    <option value="england">England</option>
    <option value="scotland">Scotland</option>
    <option value="ireland">Ireland</option>
    <option value="wales">Wales</option>
  </select>
</div>

<div class="not-selected">
  <p>Please select a country to be able to pick the region.</p>
</div>

<div class="england" id="england">
  <h3>Pick region in England</h3>
  <select>
    <option value="North">North</option>
    <option value="South">South</option>
    <option value="East">East</option>
    <option value="West">West</option>
    <option value="Midlands">Midlands</option>
  </select>
</div>

<div class="scotland" id="scotland">
  <h3>Pick region in Scotland</h3>
  <select>
    <option value="North">North</option>
    <option value="South">South</option>
  </select>
</div>

<div class="ireland" id="ireland">
  <h3>Pick region in Ireland</h3>
  <select>
    <option value="Northern">Northern</option>
    <option value="Republic">Republic</option>
  </select>
</div>

<div class="wales" id="wales">
  <h3>Pick region in Wales</h3>
  <select>
    <option value="North">North</option>
    <option value="South">South</option>
  </select>
</div>

Post a Comment for "How To Show/hide Divs With Multiple Select Options"