Show Hide Select Options Based On Previous Selection Dropdown
Thanks for reading my question... ;-) I'm building a Wordpress site that uses Custom Posts and Custom Fields to show a vehicle inventory. I would like the visitor to be able to fil
Solution 1:
subscribe to your select
elements' onchange
events: http://www.w3schools.com/jsref/event_onchange.asp. In the event handler, read the currently selected value and repopulate the other elements accordingly.
Solution 2:
I would suggest you hold the data in javascript so you only need to show the necessary options for each model without having to hide some..
I put this on jsfiddle but the site keeps breaking. The code below was tested and works though.
Ok Works now:
<scripttype="text/javascript">var vehicles = {"Cars": {
"Ford" : [ "Fiesta", "Focus", "Fusion"],
"Chevy": [ "Malibu", "Corvette", "Tahoe"],
},
"Motorcycles": {
"Honda": ["model 1", "model 2", "model 3"],
"Yamaha": ["model 1", "model 2", "model 3", "model 4"]
}
};
$(document).ready(function() {
var $vehiclesList = $("#qmt-vehicle");
var $manufList = $("#qmt-manufacturer");
var $modelList = $("#qmt-model");
var selectedType = nullvar selectedManuf = null;
$.each(vehicles, function(key, vehicle) {
$vehiclesList.append($("<option/>", {value:key,text:key}));
});
$vehiclesList.bind("change", function() {
selectedType = $(this).val();
if (selectedType && vehicles[selectedType]) {
var manufacturers = vehicles[selectedType];
$("#qmt-manufacturer option").not(":first").remove();
$("#qmt-model option").not(":first").remove();
$.each(manufacturers, function(key, manufacturer) {
$manufList.append($("<option/>", { value: key, text: key}));
});
}
});
$manufList.bind("change", function() {
var selectedManuf = $(this).val();
$("#qmt-model option").not(":first").remove();
if (selectedManuf && vehicles[selectedType] && vehicles[selectedType][selectedManuf]) {
var models = vehicles[selectedType][selectedManuf];
$.each(models, function(key, model) {
$modelList.append($("<option/>", { value: model, text: model}));
});
}
});
});
</script>
Then in your page you'd have
<labelfor="qmt-vehicle">Vehicle:</label><selectid="qmt-vehicle"name="vehicle"><option></option></select><labelfor="qmt-manufacturer">Manufacturer:</label><selectid="qmt-manufacturer"name="manufacturer"><option></option></select><labelfor="qmt-model">Model:</label><selectid="qmt-model"name="model"><option></option></select>
Post a Comment for "Show Hide Select Options Based On Previous Selection Dropdown"