JSFiddle - React, Tailwind, and code Playground
by konijn_gmail_com
HTML
<select id="whiskeyType">
</select>
<select id="whiskeySubType">
</select>
JavaScript
var whiskeys =
{
"American whiskey" :
[ "Bourbon" , "Corn whiskey" , "Rye whiskey" , "Single malt whiskey" , "Wheat whiskey" , "Blended whiskey" ],
"Irish whiskey" :
[ "Irish single malt" , "Single pot still whiskey" , "Blended whiskey" , "Single grain whiskey" ],
"Scotch whisky" :
[ "Single malt scotch" , "Grain whisky" , "Blended whisky" ]
}
function createOptionDependencies( data , parent , child )
{
//Get the 'parent' element
var parent = document.getElementById( parent );
//Assign the choices
for( var key in data )
{
var element = new Option( key , key );
parent.appendChild(element);
}
//Listen to 'parent' changes, update the child when that happens
parent.addEventListener( "change" , function(e)
{
setOptions( child , data[this.value] );
});
//Set the default suboptions
setOptions( child , data[parent.value] );
}
function setOptions( id , array )
{
//Get the element
var select = document.getElementById( id ) , i
//Remove potentially existing children, somewhat heartless
while (select.firstChild)
select.removeChild(select.firstChild);
//Add the new children
for( i = 0 ; i < array.length ; i++ )
{
var element = new Option( array[i] , array[i] );
select.appendChild(element);
}
}
createOptionDependencies( whiskeys , "whiskeyType" , "whiskeySubType" );