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

198,828

Solution 1

This will work (pure JS, appending to a div of id myDiv):

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

Solution 2

var sel = document.createElement('select');
sel.name = 'drop1';
sel.id = 'Select1';

var cars = [
  "volvo",
  "saab",
  "mercedes",
  "audi"
];

var options_str = "";

cars.forEach( function(car) {
  options_str += '<option value="' + car + '">' + car + '</option>';
});

sel.innerHTML = options_str;


window.onload = function() {
  document.body.appendChild(sel);
};

Solution 3

I have quickly made a function that can achieve this, it may not be the best way to do this but it simply works and should be cross browser, please also know that i am NOT a expert in JavaScript so any tips are great :)

Pure Javascript Create Element Solution

function createElement(){
    var element  = document.createElement(arguments[0]),
        text     = arguments[1],
        attr     = arguments[2],
        append   = arguments[3],
        appendTo = arguments[4];

    for(var key = 0; key < Object.keys(attr).length ; key++){
        var name = Object.keys(attr)[key],
             value = attr[name],
             tempAttr = document.createAttribute(name);
             tempAttr.value = value;
        element.setAttributeNode(tempAttr)
    }
    
    if(append){
        for(var _key = 0; _key < append.length; _key++) {
            element.appendChild(append[_key]);
        }
    }

    if(text) element.appendChild(document.createTextNode(text));

    if(appendTo){
        var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
        target.appendChild(element)
    }       

    return element;
}

lets see how we make this

<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>

here's how it works

    var options = [
        createElement('option', 'Volvo', {value: 'volvo'}),
        createElement('option', 'Saab', {value: 'saab'}),
        createElement('option', 'Mercedes', {value: 'mercedes'}),
        createElement('option', 'Audi', {value: 'audi'})
    ];


    createElement('select', null, // 'select' = name of element to create, null = no text to insert
        {id: 'Select1', name: 'drop1'}, // Attributes to attach
        [options[0], options[1], options[2], options[3]], // append all 4 elements
        'body' // append final element to body - this also takes a element by id without the #
    );

this is the params

createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');

This function would suit if you have to append many element, if there is any way to improve this answer please let me know.

edit:

Here is a working demo

JSFiddle Demo

This can be highly customized to suit your project!

Solution 4

This code would create a select list dynamically. First I create an array with the car names. Second, I create a select element dynamically and assign it to a variable "sEle" and append it to the body of the html document. Then I use a for loop to loop through the array. Third, I dynamically create the option element and assign it to a variable "oEle". Using an if statement, I assign the attributes 'disabled' and 'selected' to the first option element [0] so that it would be selected always and is disabled. I then create a text node array "oTxt" to append the array names and then append the text node to the option element which is later appended to the select element.

var array = ['Select Car', 'Volvo', 'Saab', 'Mervedes', 'Audi'];

var sEle = document.createElement('select');
document.getElementsByTagName('body')[0].appendChild(sEle);

for (var i = 0; i < array.length; ++i) {
  var oEle = document.createElement('option');

  if (i == 0) {
    oEle.setAttribute('disabled', 'disabled');
    oEle.setAttribute('selected', 'selected');
  } // end of if loop

  var oTxt = document.createTextNode(array[i]);
  oEle.appendChild(oTxt);

  document.getElementsByTagName('select')[0].appendChild(oEle);
} // end of for loop

Solution 5

Here's an ES6 version of the answer provided by 7stud.

const sel = document.createElement('select');
sel.name = 'drop1';
sel.id = 'Select1';

const cars = [
  "Volvo",
  "Saab",
  "Mercedes",
  "Audi",
];

const options = cars.map(car => {
  const value = car.toLowerCase();
  return `<option value="${value}">${car}</option>`;
});

sel.innerHTML = options;

window.onload = () => document.body.appendChild(sel);
Share:
198,828

Related videos on Youtube

Christos Baziotis
Author by

Christos Baziotis

Updated on April 06, 2020

Comments

  • Christos Baziotis
    Christos Baziotis about 4 years

    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?

    • Ian
      Ian almost 11 years
      Look into document.createElement and element.appendChild
    • WooCaSh
      WooCaSh almost 11 years
      @koukouloforos is my answer is helpful?
    • Christos Baziotis
      Christos Baziotis almost 11 years
      @WooCaSh it does what i am asking but i prefer if something in simple javascript.
    • John Dvorak
      John Dvorak almost 11 years
      @koukouloforos reason? If that's a commercial project, it's highly recommended to use a library.
    • Christos Baziotis
      Christos Baziotis almost 11 years
      @JanDvorak No i am just doing some testing.
    • John Dvorak
      John Dvorak almost 11 years
      @koukouloforos in which case carry on. It's good to learn how to do it the "hard" way.
  • Ian
    Ian almost 11 years
    It's a miracle! A non-jQuery solution. You might just want to set properties, instead of attributes with setAttribute(). And not that it matters, but using new Option(text, value) is a nice shortcut for creating <option> elements
  • tymeJV
    tymeJV almost 11 years
    @Ian -- Thanks for the tips, still learning pure JS, learned jQuery first unfortunately, trying to be able to do everything in pure JS as well is a bit tricky :)
  • Ian
    Ian almost 11 years
    @tymeJV Of course, just trying to help improve your answer (although great as it is). Very true though, although sometimes it feels more rewarding when you can do it without jQuery :) For anyone's reference - stackoverflow.com/questions/6936071/… . And I haven't found a need for using setAttribute()/getAttribute() unless you're working with custom attributes (including data-*) attributes. I know there are inconsistencies when using those methods as well, so I stay away
  • Zirak
    Zirak almost 11 years
    You can also add options by using selectList.add(option) (spec (scroll up a bit), mdn)
  • 7stud
    7stud almost 11 years
    A long time ago add()/remove() worked differently in different browsers, so ppk advised not to use them. I don't know what the current state of affairs is.
  • Roman Newaza
    Roman Newaza over 8 years
    This is the fastest solution and it works with large data sets.
  • 7stud
    7stud over 8 years
    @RomanNewaza, Check the speed with the forEach loop replaced by a regular old for-loop.
  • r0m4n
    r0m4n almost 6 years
    Just as a warning, if the select is generated with user created content, this is not a secure way to implement a select
  • chx
    chx about 4 years
    This is really strange, you are setting innerHTML to an array. Are you sure this doesn't need sel.innerHTML = options.join('')
  • Kevin Østerkilde
    Kevin Østerkilde about 4 years
    Yeah I'm sure. Here's an example of the code in action
  • Kevin Østerkilde
    Kevin Østerkilde about 4 years
    Using reduce is a bit overkill here innit? A map works just as well for the usecase which OP is describing.
  • JohnnyD
    JohnnyD over 3 years
    how would we be able to have a default brand lets say Saab selected?