Show/Hide using drop down list

后端 未结 3 1173
执笔经年
执笔经年 2021-01-28 21:19

Hello I am trying to use this code below. I like the code but I want the default to be DIV Area 1. I have the HTML code showing DIV Area 1 in the drop down menu but I want the

相关标签:
3条回答
  • 2021-01-28 21:25
    $('.box').hide().first().show();
    

    Or:

    $('.box').hide().filter("#divarea1").show(); 
    

    Live DEMO

    Put one of the above in the DOM ready event:

    $(function(){ /*...*/ });
    

    Or

    $(document).ready(function(){ /* ... */ });
    

    Full code: (It should answer you next question regarding how to show the selected div...)

    $(document).ready(function() {
    
        $('.box').hide().filter("#divarea1").show();
    
        $('#dropdown').change(function() {
            var selectedId= $(this).find(':selected').text().replace(/\s/g, "").toLowerCase();
            console.log(selectedId);
            $('.box').hide().filter('#' + selectedId).show();
        });
    });​
    
    0 讨论(0)
  • 2021-01-28 21:35

    could do this...

    $('.box').hide().filter(':first').show();

    0 讨论(0)
  • 2021-01-28 21:45

    A lot of complicated answers for a simple problem:

    $('.box:gt(0)').hide();

    I'd code it up like this:

     $(document).ready(function(){
         $('.box:gt(0)').hide();
    
        $('#dropdown').change(function() {
            $('.box:visible').hide();
            if ($(this).prop('selectedIndex')>0)
                $('.box').eq($(this).prop('selectedIndex')-1).show();        
        });
    });​
    

    http://jsfiddle.net/lucuma/xNZWY/

    If you remove the 1st option from your dropdown (since you are preselecting is it necessary?) it becomes a little simpler since we can remove the if

    $(document).ready(function(){
         $('.box:gt(0)').hide();
    
        $('#dropdown').change(function() {
            $('.box:visible').hide();
            $('.box').eq($(this).prop('selectedIndex')-1).show();        
        });
    });​
    
    0 讨论(0)
提交回复
热议问题