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();
  });
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><divclass="country"><h1>Pick country</h1><selectclass="country_option"><optionvalue="england">England</option><optionvalue="scotland">Scotland</option><optionvalue="ireland">Ireland</option><optionvalue="wales">Wales</option></select></div><divclass="not-selected"><p>Please select a country to be able to pick the region.</p></div><divclass="england"id="england"><h3>Pick region in England</h3><select><optionvalue="North">North</option><optionvalue="South">South</option><optionvalue="East">East</option><optionvalue="West">West</option><optionvalue="Midlands">Midlands</option></select></div><divclass="scotland"id="scotland"><h3>Pick region in Scotland</h3><select><optionvalue="North">North</option><optionvalue="South">South</option></select></div><divclass="ireland"id="ireland"><h3>Pick region in Ireland</h3><select><optionvalue="Northern">Northern</option><optionvalue="Republic">Republic</option></select></div><divclass="wales"id="wales"><h3>Pick region in Wales</h3><select><optionvalue="North">North</option><optionvalue="South">South</option></select></div>

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