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

筅森魡賤 提交于 2019-12-10 10:27:45

问题


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!


回答1:


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();
    }         
  });
});



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1117603/jquery-showing-a-div-if-a-specific-a-select-option-is-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!