JSFiddle - React, Tailwind, and code Playground

by russduza

HTML

<h3>Populating Two Complementary Selects</h3>

<p>This example shows how to populate two complementary select boxes from a data source and how to respond to user choice on the select box. Your task is to make the two complementary SELECT controls work in this way: selecting a value in the first populates the second with appropriate choices. In the first box you will use the "boyname" and "girlname" options as a reference in the HTML. In the second box you will choose three boy names and three girls names and display them as options.</p>

<form action="#" id="theForm" name="firstForm">
<div id="selects">
            <div id="select1Div" style="float:left;margin-right:15px;"> Select
              Your &lt;something&gt; <br>
              <select onchange="handleFirstSelect()" name="firstSelect" id="firstSelect">
                <option>----</option>
				<option value="boyname">Boy Names</option>
				<option value="girlname">Girl Names</option>
              </select>
            </div>
            <div id="select2Div"> Select Your &lt;somethingElse&gt;
              <br>
              <select name="secondSelect" id="secondSelect">
                <option>----</option>
                &nbsp;
              </select>
            </div>
          </div>
          <br>

JavaScript

window.onload=function(){

function handleFirstSelect(){
	var firstSelect = document.getElementById("firstSelect").value;
	document.getElementById("secondSelect").innerHTML = "<option>----</option>";
	var list =[];
	if(firstSelect =="boyname"){
		list =[ "John","Jack", "Jorge"]
	}else if(firstSelect =="girlname"){
		list =[ "Jerry","Julia", "Janelle"]
	}
	
	for (var i = 0; i<list.length; i++){
    var opt = document.createElement('option');
    opt.value = list[i];
    opt.innerHTML = list[i];
    document.getElementById("secondSelect").appendChild(opt);
}
}
}