//this would be an array of JSON objects for the measures for a type, in this case its fruits that have a specific color
var fruits = [
{"id" : "1","colorId" : "1","name" : "Apple"}, //json object 1
{"id" : "2","colorId" : "1","name" : "Strawberry"}, //json object 2
{"id" : "3","colorId" : "2","name" : "Blueberry"}, //json object 3
{"id" : "4","colorId" : "3","name" : "Banana"}, //json object 4
{"id" : "5","colorId" : "3","name" : "Mango"} //json object 5
];
//bind the change event to the function
$("#one").on("change", function(){
var val = $(this).val(); //cache the value so you dont call jquery for every option you loop through
var $two = $("#two"); //cache the second dropwown, the $ before the var name means its wrapped in jquery, its a good convention to follow
//remove current options
$two.children().remove();
//loop through the json objects, checking the id of the first select
for(var i = 0; i < fruits.length; i++){
if(val === fruits[i].colorId){
$two.append(createOption(fruits[i].id,fruits[i].name)); //add the new option
}
}
});
function createOption(id,value){
return $("<option value=" + id + ">" + value + "</option>"); //passing HTML to jquery returns a new element
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.