JSFiddle - React, Tailwind, and code Playground

by bittersweetryan

HTML

<select name="select1" id="one">
    <option value="">Select One...</option>
    <option value="1">Red</option>
    <option value="2">Blue</option>
    <option value="3">Yellow</option>
</select>
<br>
<select name="select2" id="two"></select>

JavaScript

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