using jquery how do I filter a dropdown field based on value selected from another dropdown field

前端 未结 3 425
忘了有多久
忘了有多久 2020-12-06 03:52

I am just missing something.

Very simple or so I thought - using jquery - Based on the value selected in the Workers dropdown, I want to display on

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-06 04:26

    You need a data structure to map the relationship between worker and the fruit. Something like below,

    var workerandFruits = {
        Roy: ["Apples", "Peaches"],
        John: ["Oranges", "Pears", "Peaches", "Nut"]
    }
    

    Then you need to write an onchange handler for $('select[name=Select1') inside which you need to filter the $('select[name=Select2]) options based on the selected options text in Select1 ($(this).find('option:selected').text();).

    Now using the workerandFruits var you can determine the fruits that the selected worker prefer and populate the Select2 based on that.

    $workers.change(function () {
        var $selectedWorker = $(this).find('option:selected').text();
        $fruits.html($fruitsList.filter(function () {
             return $.inArray($(this).text(), workerandFruits[$selectedWorker]) >= 0;
        }));
    });
    

    DEMO: http://jsfiddle.net/tKU26/

提交回复
热议问题