Form Handling - Populating a Select Box

by somya_kashyap3

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 &lt;something&gt;&nbsp;&nbsp;
        <br/>
        <select name="firstSelect" id="firstSelect">
            <option>----</option>&nbsp;</select>
    </div> <span id="feedback"></span>
    <br/>
    <br/>
    <button type="submit" id="submitBtn" name="submit">Submit</button>
</form>

CSS

#vegForm {


    border: 1px solid orange;


    padding: 2em;


    background-color: #ffffaa;


}

JavaScript

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!"
 });