show/hide div based on select option jquery

后端 未结 4 1523
说谎
说谎 2020-11-27 13:08

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



        
相关标签:
4条回答
  • 2020-11-27 13:52

    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();
        });
    
    });
    
    0 讨论(0)
  • 2020-11-27 13:52

    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();
    
    0 讨论(0)
  • 2020-11-27 13:54

    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
    
                  }
    });
    
    0 讨论(0)
  • 2020-11-27 14:03
    <script>  
    $(document).ready(function(){
        $('#colorselector').on('change', function() {
          if ( this.value == 'red')
          {
            $("#divid").show();
          }
          else
          {
            $("#divid").hide();
          }
        });
    });
    </script>
    

    Do like this for every value

    0 讨论(0)
提交回复
热议问题