javascripthtmldrop-down-menuhtml-select

How to add Drop-Down list (<select>) programmatically?


I want to create a function in order to programmatically add some elements on a page.

Lets say I want to add a drop-down list with four options:

<select name="drop1" id="Select1">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

How can I do that?


Solution

  • This will work (pure JS, appends to document body):

    Demo: http://jsfiddle.net/4pwvg/

    var myParent = document.body;
    
    //Create array of options to be added
    var array = ["Volvo","Saab","Mercades","Audi"];
    
    //Create and append select list
    var selectList = document.createElement("select");
    selectList.id = "mySelect";
    myParent.appendChild(selectList);
    
    //Create and append the options
    for (var i = 0; i < array.length; i++) {
        var option = document.createElement("option");
        option.value = array[i];
        option.text = array[i];
        selectList.appendChild(option);
    }