简体   繁体   中英

jQuery: Showing a div if a specific a <select> option is selected?

I'm working on the address page for a shopping cart. There are 2 <select> boxes, one for Country, one for Region.

There are 6 standard countries available, or else the user has to select "Other Country". The <option> elements all have a numeric value - Other Country is 241. What I need to do is hide the Region <select> if the user selects Other Country, and also display a textarea.

Any help MUCH appreciated!

You need to bind a function to the select list so that when it changes, your function decides if the div should be shown. Something like this ( untested, hopefully syntactically close ). Here's a live example .

$(document).ready( function() {
  $('#YourSelectList').bind('change', function (e) { 
    if( $('#YourSelectList').val() == 241) {
      $('#OtherDiv').show();
    }
    else{
      $('#OtherDiv').hide();
    }         
  });
});

It's the same principle as this question . You just need to connect to the change on the select , check the val() and hide()/show() the div.

In my opinion, you don't really need jQuery for this.

This simple JavaScript code will do the trick:

document.getElementById('country_id').onchange = function()
{
    if (this.options[this.selectedIndex].value == 241) {
        document.getElementById('region_id').style.display = 'block';
    } else {
        document.getElementById('region_id').style.display = 'none';
    }
}

value works for most browsers, but yes, for older browsers you need select.options[select.selectedIndex].value . I updated my script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM