Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
953 views
in Technique[技术] by (71.8m points)

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

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 only certain values in the Fruit Options dropdown.

So for example if Roy is selected from the Workers dropdown, I only want Apples and Peaches to appear as options within the Fruit Options Dropdown If John is selected from the Workers dropdown, then only Oranges, Pears, Peaches, Nuts to appear as options within the Fruit Options Dropdown.

How do I correctly, using jquery, filter the Fruit Options drop based on the selection of the Worker dropdown?

My jfiddle is here: http://jsfiddle.net/justmelat/BApMM/1/

My Code:

 <form method="post">
    Worker:  <select  id="workers" name="Select1">
    <option>Roy</option>
    <option>John</option>
<option>Dave</option>
    </select>
</form>
<br><br>
<form method="post">
    Fruit Options: <select id="fruitopts" name="Select2">
    <option>Apples</option>
    <option>Oranges</option>
    <option>Pears</option>
    <option>Peaches</option>
    <option>Grapes</option>
    <option>Melons</option>
    <option>Nut</option>
    <option>Jelly</option>
    </select></form>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...