最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: Showing a div if a specific a <select> option is selected? - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question edited Sep 8, 2022 at 15:34 Daniel Widdis 9,14013 gold badges48 silver badges68 bronze badges asked Jul 13, 2009 at 3:37 SamalahSamalah
Add a ment  | 

3 Answers 3

Reset to default 6

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.

发布评论

评论列表(0)

  1. 暂无评论