Form Handling - Populating a Select Box
by jrl2000
HTML
<h3>Populating a Select</h3>
<p>This example shows how to populate a select box from a data soruce (in this case a JSON object), and how to respond to user choice on the select box.</p>
<p>Notice that the select is empty in the HTML, and is populated from the JSON object using standard DOM element creation methods.</p>
<form action="#" id="theForm" name="firstForm">
<div id="select1Div">Select Your <something>
<br/>
<select name="firstSelect" id="firstSelect">
<option>----</option> </select>
</div> <span id="feedback"></span>
<br/>
<br/>
<button type="submit" id="submitBtn" name="submit">Submit</button>
</form>
<form action="#" id="theForm2" name="secondForm">
<div id="select2Div">Select Your <something>
<br/>
<select name="secondSelect" id="secondSelect">
<option>----</option> </select>
</div> <span id="feedback"></span>
<br/>
<br/>
<button type="submit" id="submitBtn2" name="submit2">Submit</button>
</form>
CSS
#vegForm {
border: 1px solid orange;
padding: 2em;
background-color: #ffffaa;
}
JavaScript
var sel1 = document.getElementById("firstSelect");
var sel2 = document.getElementById("secondSelect");
var selectListCars = {
"cars": ["Toyota", "Acura", "Ford", "BMW"]
}
var Toyota = ["Camry", "4Runner", "Highlander"];
var Acura = ["MDX", "RDX", "Sedan"];
var Ford = ["Escort", "F-150", "Turus"];
var BMW = ["M3", "M5", "M7"];
var makes = {
"makes": [Toyota, Acura, Ford, BMW]
}
/* First, populate the select.
For each element in the "selectList.fruits" array,
we will create an <option> element, give it a
text node that contains its label, set the
'value' attribute on our new <option> element, and
finally, add it to the <select> element.
*/
for (var i = 0; i < selectListCars.cars.length; i++) {
//create <option>
var s = document.createElement("option");
// create text node
var t = document.createTextNode(selectListCars.cars[i]);
// add text node to <option>
s.appendChild(t);
// set value="" on the <option>
s.setAttribute("value", selectListCars.cars[i]);
// add the new <option> to the <select>
sel1.appendChild(s);
}
// This part will react to user selections on our drop-down list
// and write to the page
sel1.addEventListener("change", function(e) {
var val = this.value;
if (val === "Toyota"){
for (var i = 0; i < selectListToyota.cars.length; i++) {
//create <option>
var s = document.createElement("option");
// create text node
var t = document.createTextNode(selectListToyota.cars[i]);
// add text node to <option>
s.appendChild(t);
// set value="" on the <option>
s.setAttribute("value", selectListToyota.cars[i]);
// add the new <option> to the <select>
sel2.appendChild(s);
}
} else if (val === "Acura"){
for (var i = 0; i < selectListAcura.cars.length; i++) {
//create <option>
var s = document.createElement("option");
// create text node
var t =...