Show a second dropdown based on previous dropdown selection

前端 未结 4 1211
庸人自扰
庸人自扰 2020-11-28 09:34

First off, I hate bringing up an issue that has already been dealt with, but you should know the other options I have found on this site aren\'t working for me.

Basi

4条回答
  •  情话喂你
    2020-11-28 10:09

    One way or another, you've already ended up with what's probably the easiest HTML markup to use for the job:

    
    

    and then one container for each possibility of .

    // For Airman
    // For Senior Airman

    ... etc etc...

    I'd use this same layout for everything that depends on which is selected; the unique-line-of-text you want, the other-select-box, etc etc. I'd wrap each one in a container element, so you can easily target all the elements as one.

    Line of text for Airman
    Line of text for Senior Airman

    Now whack a identifier to each of the

    's we've got, so when the "Airman" is selected, we know which
    's are the Airmans (so we know to show those ones!)

    Line of text for Airman
    Line of text for Senior Airman

    And add the same identifier to the 's of the

    Now we've got this markup, applying the JavaScript for the hiding/showing is so easy!

    $(document).ready(function () {
        $('#Rank').bind('change', function () {
            var elements = $('div.container').children().hide(); // hide all the elements
            var value = $(this).val();
    
            if (value.length) { // if somethings' selected
                elements.filter('.' + value).show(); // show the ones we want
            }
        }).trigger('change'); // Setup the initial states
    });
    

    Done; checkout an example: http://jsfiddle.net/3UWk2/1/

    An update for your comment

    The reason your attempt to change the code like you did didn't work is because we've currently got no event handler bound to the 2nd level

    You need to basically repeat everything we've just done for the first level nav, for the second level nav. Instead of using an #id selector for the element to target, and #id's have to be unique:

    $('.second-level-select').bind('change', function () {
        var elements = $('div.second-level-container').children().hide(); // hide all the elements
        var value = $(this).val();
    
        if (value.length) { // if somethings' selected
            elements.filter('.' + value).show(); // show the ones we want
        }
    }).trigger('change'); // Setup the initial states
    

    We've also had to change the name of the div.container, to stop the

    提交评论

提交回复
热议问题