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