show/hide div based on select option jquery

独自空忆成欢 提交于 2019-11-26 06:28:33

问题


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>

回答1:


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

});



回答2:


<script>  
$(document).ready(function(){
    $('#colorselector').on('change', function() {
      if ( this.value == 'red')
      {
        $("#divid").show();
      }
      else
      {
        $("#divid").hide();
      }
    });
});
</script>

Do like this for every value




回答3:


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:


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


来源:https://stackoverflow.com/questions/2975521/show-hide-div-based-on-select-option-jquery

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