3

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>
user1176783
  • 673
  • 4
  • 19
  • 39
  • 5
    Have you written any JavaScript yet or are you asking us to write the whole thing for you? – j08691 Jun 07 '13 at 19:55
  • I don't see any relation explicit relation between the options. Also this is not a homework site – Sushanth -- Jun 07 '13 at 19:56
  • you need to have some kind of data structure which relates the workers to the fruits, then query this structure for what you want – stackErr Jun 07 '13 at 19:56
  • Do you populate both the drop-down controls dynamically or are those static? You must have 2 methods one to populate the workers ddl and another to populate fruits ddl. Something like PopulateWorker() and PopulateFruitsByWorkerId(Int WorkerId) – Learner Jun 07 '13 at 19:58
  • 1
    Check this out and update it to match your needs: http://jsfiddle.net/4Zw3M/1/ – Learner Jun 07 '13 at 20:03

3 Answers3

5

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/

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
  • VEga, I think you and Leamer have me going in the right direction now, I didn't set up the array port correctly. I am testing in the real code now. – user1176783 Jun 07 '13 at 21:31
  • You can use `$(this).val()` instead of `$(this).find('option:selected').text()`. – Jamie Kitson Jun 13 '14 at 10:44
  • @JamieKitson Nope, The OP want the text NOT the value of the selected option. For ex: `` - Here OP wants the text "Apple Fruit", `.val` will return you "apple". – Selvakumar Arumugam Jun 13 '14 at 16:37
  • (S)He doesn't mention "text" anywhere in the question, the title and second paragraph specify value, not text. – Jamie Kitson Jun 16 '14 at 09:36
  • @JamieKitson I missed to read the question last time, but the OP is actually about filter the 2nd drop down based on 1st drop down selection. Also the example doesn't have value set for any of the option tag which is why the answer uses text to map the two drop down. – Selvakumar Arumugam Jun 16 '14 at 12:41
  • The value of the selected option will be the text where there is no value specified. Try the fiddle, it works. http://jsfiddle.net/tKU26/79/ – Jamie Kitson Jun 17 '14 at 11:53
  • @JamieKitson [That works because the browser take the value as text if the value is not provided.](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option#attr-value) ex: http://jsfiddle.net/kJdU4/ -- _The `.val()` method is primarily used to get the **values** of form elements such as input, select and textarea._ ~ from jQuery docs. Why would i use `.val` to get the `text`? This answer is basically to work best for the OP. – Selvakumar Arumugam Jun 17 '14 at 14:15
  • Because `.val()` is simpler, shorter and easier to read and understand than `.find('option:selected').text()`. Besides, as we've already discussed, the OP states they want the value. – Jamie Kitson Jun 18 '14 at 10:17
  • @JamieKitson I still cannot agree to use `.val()` to get the text content. The OP states value but there is no `value` attribute set for any of the option. – Selvakumar Arumugam Jun 18 '14 at 15:59
2

Do something like this:

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

Learner
  • 3,904
  • 6
  • 29
  • 44
0

Using AJAX is a great way to do what you are asking.

Please forgive me if you already know this but in jQuery/javascript, you:

  • grab the value of the first select box

  • use AJAX code to send that to a secondary PHP file, which uses the data it receives to write some HTML code based on what the user chose

  • the newly constructed HTML is ECHOed back to the ajax routine, where it is received inside a success function

  • Inside the success function, you can use jQuery to replace the contents of the second dropdown

Here is a detailed example, with explanations

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • possibly he is not using any sort of data structure, ajax and php wouldn't help in that case. – Learner Jun 07 '13 at 20:04
  • 1
    Thanks for the gentle comment. You are right, good point. Your solution is very elegant, although somewhat complex for a new coder. – cssyphus Jun 07 '13 at 20:21