简体   繁体   中英

Returning data based on multiple drop down menus

I have a couple of drop down menus that once selected should return different types of data based on the user's selection. Here's the format:

var data = {
        name :{
                first:{
                    itemOne    : [],
                    itemTwo    : [],
                    itemThree  : []
                }

                second:{
                    itemOne    : [],
                    itemTwo    : [],
                    itemThree  : []
                }

                third:{
                    itemOne    : [],
                    itemTwo    : [],
                    itemThree  : []
                }
        }
 }

So there are two drop down menus. The first menu has the names 'first', 'second', 'third' and the second menu has 'itemOne', 'itemTwo', and 'itemThree'. So I would like data to be returned or updated each time the user selects from these two drop down menus. I currently have the following for just one menu:

 $('#selectMenu').on('change', function (event) {

        var selectedData = data[$(this).val()];
        console.log(selectedData);

        });

How could I make this so that the data returned depends on both drop down menus rather than just one?

Edit: HTML Markup

<span display: inline-block; width: 150px>
  <center>
    <select id="selectMenuTwo"> 
        <option value="first">first</option>
        <option value="second">second</option>
        <option value="third">third</option>
    </select>

    <select id="selectMenu">
        <option>Menu 1</option>
        <option value="itemOne">Item One</option>
        <option value="itemTwo">Item Two</option>
        <option value="itemThree">Item Three</option>
    </select>
 </center>
</span>

You could handle the change event on both dropdowns and then just look at the other menu's selected value inside the "change" function.

    $('#selectMenu1').on('change', function (event) {

        var menu2SelectedData = $('#selectMenu2').val();
        var selectedData = data[$(this).val()];
        console.log(selectedData);

    });

    $('#selectMenu2').on('change', function (event) {

        var menu1SelectedData = $('#selectMenu1').val();
        var selectedData = data[$(this).val()];
        console.log(selectedData);

    });

or maybe something like this would be even cleaner...

    // handle change for both menues
    $('#selectMenu1, #selectMenu2').on('change', function (event) {

        var menu1SelectedData = $('#selectMenu1').val();
        var menu2SelectedData = $('#selectMenu2').val();
        var dataForDropdown = data.name[menu1SelectedData][menu2SelectedData];

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM