<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>
var sel1 = document.getElementById("firstSelect");
var selectList = {
fruits: ["Apple", "Banana", "Grapefruit", "Plantain"]
}
/* 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 < selectList.fruits.length; i++) {
//create <option>
var s = document.createElement("option");
// create text node
var t = document.createTextNode(selectList.fruits[i]);
// add text node to <option>
s.appendChild(t);
// set value="" on the <option>
s.setAttribute("value", selectList.fruits[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;
document.getElementById('feedback').innerHTML = val + "s are good!"
});
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.