Problem
Because I don’t want to manually construct all of the option tags, I’d like this javascript to create choices from 12 to 100 in a choose with id=”mainSelect.” Could you point me in the right direction? Thanks
function selectOptionCreate() {
var age = 88;
line = "";
for (var i = 0; i < 90; i++) {
line += "<option>";
line += age + i;
line += "</option>";
}
return line;
}
Asked by jacktheripper
Solution #1
This might be accomplished 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.
I did a JS Perf comparison of my and Sime Vidas’ answers because I believed his looked a little more understandable/intuitive than mine, and I was curious how that would convert into implementation. Mine is slightly faster according to Chromium 14/Ubuntu 11.04, however other browsers/platforms may produce different results.
In response to the OP’s comment, I’ve made the following changes:
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.
Finally (after a long wait…), a technique that extends the HTMLSelectElement prototype in order to chain the populate() function to the DOM node as a method:
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:
Answered by David Thomas
Solution #2
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: If you wish to use this code again, here’s the function:
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/
Answered by Šime Vidas
Solution #3
The simplest and most intuitive method would be:
With additional parameters to the used functions, you may additionally separate the name and the value, or add items to the beginning of the list: new Option(text, value, defaultSelected, selected); HTMLSelect Element.add(item[, before]); new Option(text, value, defaultSelected, selected); new Option(text, value, defaultSelected, selected); new Option(text, value, defaultSelected, selected
Answered by user
Solution #4
Doing DOM modifications inside a loop isn’t recommended because it can be costly in large datasets. Instead, I’d do something along these lines:
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:
Answered by thdoan
Solution #5
To minimize frequent re-renderings of the page, I’d avoid doing DOM activities in a loop.
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: I removed the function to demonstrate how you can simply assign the html you’ve created to a different select element, avoiding the looping caused by repeating the function call.
Answered by kinakuta
Post is based on https://stackoverflow.com/questions/8674618/adding-options-to-select-with-javascript