show/hide div based on select option jquery

2019-01-06 11:01发布

Here is my code. Why it doesn't work?

<Script> 
   $('#colorselector').change(function() {
        $('.colors').hide();
        $('#' + $(this).val()).show();
 });
</Script>
<Select id="colorselector">
   <option value="red">Red</option>
   <option value="yellow">Yellow</option>
   <option value="blue">Blue</option>
</Select>
<div id="red" class="colors" style="display:none"> .... </div>
<div id="yellow" class="colors" style="display:none"> ... </div>
<div id="blue" class="colors" style="display:none"> ... </div>

4条回答
等我变得足够好
2楼-- · 2019-01-06 11:41

You're running the code before the DOM is loaded.

Try this:

Live example:

http://jsfiddle.net/FvMYz/

$(function() {    // Makes sure the code contained doesn't run until
                  //     all the DOM elements have loaded

    $('#colorselector').change(function(){
        $('.colors').hide();
        $('#' + $(this).val()).show();
    });

});
查看更多
Bombasti
3楼-- · 2019-01-06 11:47

To show the div while selecting one value and hide while selecting another value from dropdown box: -

 $('#yourselectorid').bind('change', function(event) {

           var i= $('#yourselectorid').val();

            if(i=="sometext") // equal to a selection option
             {
                 $('#divid').show();
             }
           elseif(i=="othertext")
             {
               $('#divid').hide(); // hide the first one
               $('#divid2').show(); // show the other one

              }
});
查看更多
戒情不戒烟
4楼-- · 2019-01-06 11:50
<script>  
$(document).ready(function(){
    $('#colorselector').on('change', function() {
      if ( this.value == 'red')
      {
        $("#divid").show();
      }
      else
      {
        $("#divid").hide();
      }
    });
});
</script>

Do like this for every value

查看更多
不美不萌又怎样
5楼-- · 2019-01-06 12:02

You are missing a :selected on the selector for show() - see the jQuery documentation for an example of how to use this.

In your case it will probably look something like this:

$('#'+$('#colorselector option:selected').val()).show();
查看更多
登录 后发表回答