Using jquery, how do I filter a dropdown menu field based on a value selected from another dropdown field

I just missed something.

Very simple or the way I thought - using jquery - based on the value selected in the Workers drop-down list , I want to display only certain values ​​in the Fruit options drop-down list .

So, for example, if Roy is selected from the Workers drop-down list , I want apples and peaches to be displayed as options in the Fruit options Drop If John is selected in the Workers drop-down list , only oranges, pears, peaches, nuts are displayed in the Fruit options dialog box .

How to correctly, using jquery, filter the Fruit Settings option based on the selection of the Work drop-down list?

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

My code is:

 <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>
+3
source share
3 answers

. - ,

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

onchange $('select[name=Select1'), $('select[name=Select2]) Select1 ($(this).find('option:selected').text();).

, workerandFruits var, , , Select2 .

$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/

+4

- :

<select id="worker"></select>
<select id="fruits"></select>

var data = [ // The data
    ['Roy', [
        'Apples','Peaches'
    ]],
    ['John', [
        'Oranges', 'Pears', 'Peaches', 'Nuts'
    ]]
];

$a = $('#worker'); // The dropdowns
$b = $('#fruits');

for(var i = 0; i < data.length; i++) {
    var first = data[i][0];
    $a.append($("<option>"). // Add options
       attr("value",first).
       data("sel", i).
       text(first));
}

$a.change(function() {
    var index = $(this).children('option:selected').data('sel');
    var second = data[index][1]; // The second-choice data

    $b.html(''); // Clear existing options in second dropdown

    for(var j = 0; j < second.length; j++) {
        $b.append($("<option>"). // Add options
           attr("value",second[j]).
           data("sel", j).
           text(second[j]));
    }
}).change(); // Trigger once to add options at load of first choice

http://jsfiddle.net/xRTAk/

+2

AJAX - , .

, , , jQuery/javascript :

  • AJAX PHP, HTML ,

  • HTML ECHOed ajax, success

  • success jQuery

0

Source: https://habr.com/ru/post/1568874/


All Articles