258

I want this javascript to create options from 12 to 100 in a select with id="mainSelect", because I do not want to create all of the option tags manually. Can you give me some pointers? Thanks

function selectOptionCreate() {

  var age = 88;
  line = "";
  for (var i = 0; i < 90; i++) {
    line += "<option>";
    line += age + i;
    line += "</option>";
  }

  return line;
}
3
  • see stackoverflow.com/questions/170986/…
    – smnbss
    Dec 29, 2011 at 23:22
  • 20
    Voting to reopen, as the linked 'duplicate' only has jQuery-based answers, whereas this one requires (or at least implies a requirement of) plain JavaScript. Jan 1, 2012 at 21:55
  • 3
    Great answer here: mySelect.options[mySelect.options.length] = new Option('Text 1', 'Value1');
    – ruffin
    Oct 6, 2015 at 20:21

13 Answers 13

389

You could achieve this with a simple for loop:

var min = 12,
    max = 100,
    select = document.getElementById('selectElementId');

for (var i = min; i<=max; i++){
    var opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = i;
    select.appendChild(opt);
}

JS Fiddle demo.

JS Perf comparison of both mine and Sime Vidas' answer, run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.


Edited in response to comment from OP:

[How] do [I] apply this to more than one element?

function populateSelect(target, min, max){
    if (!target){
        return false;
    }
    else {
        var min = min || 0,
            max = max || min + 100;

        select = document.getElementById(target);

        for (var i = min; i<=max; i++){
            var opt = document.createElement('option');
            opt.value = i;
            opt.innerHTML = i;
            select.appendChild(opt);
        }
    }
}
// calling the function with all three values:
populateSelect('selectElementId',12,100);

// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');

// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);

JS Fiddle demo.

And, finally (after quite a delay...), an approach extending the prototype of the HTMLSelectElement in order to chain the populate() function, as a method, to the DOM node:

HTMLSelectElement.prototype.populate = function (opts) {
    var settings = {};

    settings.min = 0;
    settings.max = settings.min + 100;

    for (var userOpt in opts) {
        if (opts.hasOwnProperty(userOpt)) {
            settings[userOpt] = opts[userOpt];
        }
    }

    for (var i = settings.min; i <= settings.max; i++) {
        this.appendChild(new Option(i, i));
    }
};

document.getElementById('selectElementId').populate({
    'min': 12,
    'max': 40
});

JS Fiddle demo.

References:

3
  • @Jack: agreed, and I've used that approach in the latter edit :) May 18, 2014 at 1:42
  • Also, extending host prototypes (while tempting) is considered a bad idea.
    – RobG
    Mar 30, 2016 at 6:09
  • I think this should be updated to use innerText instead of innerHTML to avoid cross-site scripting vulnerabilities. What do you think @DavidThomas? Mar 14, 2017 at 3:08
60

The most concise and intuitive way would be:

var selectElement = document.getElementById('ageselect');

for (var age = 12; age <= 100; age++) {
  selectElement.add(new Option(age));
}
Your age: <select id="ageselect"><option value="">Please select</option></select>

You can also differentiate the name and the value or add items at the start of the list with additional parameters to the used functions:
HTMLSelect​Element​.add(item[, before]);
new Option(text, value, defaultSelected, selected);

28

Here you go:

for ( i = 12; i <= 100; i += 1 ) {
    option = document.createElement( 'option' );
    option.value = option.text = i;
    select.add( option );
}

Live demo: http://jsfiddle.net/mwPb5/


Update: Since you want to reuse this code, here's the function for it:

function initDropdownList( id, min, max ) {
    var select, i, option;

    select = document.getElementById( id );
    for ( i = min; i <= max; i += 1 ) {
        option = document.createElement( 'option' );
        option.value = option.text = i;
        select.add( option );
    }
}

Usage:

initDropdownList( 'mainSelect', 12, 100 );

Live demo: http://jsfiddle.net/mwPb5/1/

1
  • how do i apply this to more than one element? Dec 29, 2011 at 23:40
14

I don't recommend doing DOM manipulations inside a loop -- that can get expensive in large datasets. Instead, I would do something like this:

var elMainSelect = document.getElementById('mainSelect');

function selectOptionsCreate() {
  var frag = document.createDocumentFragment(),
    elOption;
  for (var i=12; i<101; ++i) {
    elOption = frag.appendChild(document.createElement('option'));
    elOption.text = i;
  }
  elMainSelect.appendChild(frag);
}

You can read more about DocumentFragment on MDN, but here's the gist of it:

It is used as a light-weight version of Document to store a segment of a document structure comprised of nodes just like a standard document. The key difference is that because the document fragment isn't part of the actual DOM's structure, changes made to the fragment don't affect the document, cause reflow, or incur any performance impact that can occur when changes are made.

6

The one thing I'd avoid is doing DOM operations in a loop to avoid repeated re-renderings of the page.

var firstSelect = document.getElementById('first select elements id'),
    secondSelect = document.getElementById('second select elements id'),
    optionsHTML = [],
    i = 12;

for (; i < 100; i += 1) {
  optionsHTML.push("<option value=\"Age" + i + "\">Age" + i + "</option>";
}

firstSelect.innerHTML = optionsHTML.join('\n');
secondSelect.innerHTML = optionsHTML.join('\n');

Edit: removed the function to show how you can just assign the html you've built up to another select element - thus avoiding the unnecessary looping by repeating the function call.

8
  • how do i apply this to more than one element? Dec 29, 2011 at 23:41
  • Not sure I follow - you want to add the same options to more than one select element?
    – kinakuta
    Dec 29, 2011 at 23:43
  • Yeah, I want to boxes with the same options Dec 29, 2011 at 23:49
  • I factored it into a function you can call where you just pass in the id of the select element you want to append the options to.
    – kinakuta
    Dec 29, 2011 at 23:54
  • 2
    That's what documentFragment is made for. You can easily modify the accepted answer so that options would be appended to documentFragment at first, preventing multiple renderings. Jan 6, 2014 at 14:44
5

When you create a new Option object, there are two parameters to pass: The first is the text you want to appear in the list, and the second the value to be assigned to the option.

var myNewOption = new Option("TheText", "TheValue");

You then simply assign this Option object to an empty array element, for example:

document.theForm.theSelectObject.options[0] = myNewOption;
4

See: What is the best way to add options to a select from an array with jQuery?

$('#mySelect')
      .append($('<option>', { value : key })
      .text(value)); 
4
var selectElement = document.getElementById('ageselect');

for (var age = 12; age <= 100; age++) {
  selectElement.add(new Option(age, age));
}


Your age: <select id="ageselect"><option value="">Please select</option></select>

Notice the value was added as a second parameter to new Option

0

None of the above solutions worked for me. Append method didn't give error when i tried but it didn't solve my problem. In the end i solved my problem with data property of select2. I used json and got the array and then give it in select2 element initialize. For more detail you can see my answer at below post.

https://stackoverflow.com/a/41297283/4928277

0

Often you have an array of related records, I find it easy and fairly declarative to fill select this way:

selectEl.innerHTML = array.map(c => '<option value="'+c.id+'">'+c.name+'</option>').join('');

This will replace existing options.
You can use selectEl.insertAdjacentHTML('afterbegin', str); to add them to the top instead.
And selectEl.insertAdjacentHTML('beforeend', str); to add them to the bottom of the list.

IE11 compatible syntax:

array.map(function (c) { return '<option value="'+c.id+'">'+c.name+'</option>'; }).join('');
0

for (let i = 12; i< 101; i++){
    let html = ""
    html += `
        <option value="${i}">${i}</option>
    `
    mainSelect.innerHTML += html
}
const mainSelect = document.getElementById("mainSelect")
This is a very easy-to-understand way to solve your problem! Hope it heps:)

0

In 2024 I would do it like this:

const elmainSelect = document.getElementById('mainSelect');
for (var i = 12; i < 101; i++) Object.assign(elmainSelect.appendChild(document.createElement('option')), {value: i, text: i});

const elmainSelect = document.getElementById('mainSelect');
for (var i = 12; i < 101; i++) Object.assign(elmainSelect.appendChild(document.createElement('option')), { value: i + 159, text: i });
elmainSelect.value = 171;
elmainSelect.addEventListener('change', () => document.getElementById('blink').innerHTML = Number(elmainSelect.value) === 182 ? `Nobody likes you when you're twenty-three` : 'My friends say I should act my age');
What's my age again?
<select id="mainSelect"></select>
<div id="blink"></div>

0

IMO another way how to do this

const select_ = document.querySelector('select'),
      output_ = document.querySelector('output span');

window.onload = _=> {
  // const options = new Array(89).fill().map((_, i) => `<option>${i+12}</option>`).join('');
  const options = Array.from({length: 89}, (_, i) => `<option>${i+12}</option>`).join('');
  select_.insertAdjacentHTML('beforeend', options);
};

select_.onchange = _=> {
  if (select_.value)
    output_.textContent = select_.value;
};
output { display: block; margin-top: 1rem; }
output span { font-weight: 700; }
<select>
  <option selected disabled>Make a choice</option>
</select>
<output>You chose: <span></span></output>

Not the answer you're looking for? Browse other questions tagged or ask your own question.