que podría lograr esto con un simple bucle for
:
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 comparación de mine y Sime Vidas' answer, se ejecuta porque pensé que se veía un poco más comprensible/intuitivo que el mío y me preguntaba cómo se traduciría en la implementación. Según Chromium 14/Ubuntu 11.04 la mina es algo más rápida, sin embargo, es probable que otros navegadores/plataformas tengan resultados diferentes.
Editado en respuesta a las observaciones de la OP:
[Cómo] qué [I] se aplica esto a más de un elemento?
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.
Y, finalmente (después de un retraso bastante ...), un enfoque que se extiende el prototipo de la HTMLSelectElement
con el fin de la cadena de la función populate()
, como un método, para el nodo DOM:
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 .
Referencias:
ver http://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from -an-array-with-jquery – smnbss
Votación para volver a abrir, ya que el 'duplicado' vinculado solo tiene respuestas basadas en jQuery, mientras que este requiere (o al menos implica un requisito de) JavaScript simple. –
[Gran respuesta aquí] (http://stackoverflow.com/a/17730724/1028230): 'mySelect.options [mySelect.options.length] = new Opción ('Text 1', 'Value1'); ' – ruffin