si potrebbe ottenere questo con un semplice for
ciclo:
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 confronto di entrambi i miei e Sime Vidas' answer, eseguire perché ho pensato che il suo sembrava un po 'più comprensibile/intuitivo del mio e mi chiedevo come questo si tradurrebbe in attuazione. Secondo Chromium 14/Ubuntu 11.04 il mio è un po 'più veloce, altri browser/piattaforme hanno probabilmente risultati diversi.
Redatta in risposta al commento da OP:
[Come] fare [I] applicare questo per più di 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.
E, infine (dopo un certo ritardo ...), un approccio estende il prototipo del HTMLSelectElement
per catena funzione populate()
, come metodo, al 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 .
Riferimenti:
fonte
2011-12-29 23:23:31
vedere http://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from -an-array-with-jquery – smnbss
Votazione per riaprire, poiché il 'duplicato' collegato ha solo risposte basate su jQuery, mentre questo richiede (o almeno implica un requisito di) JavaScript semplice. –
[Ottima risposta qui] (http://stackoverflow.com/a/17730724/1028230): 'mySelect.options [mySelect.options.length] = new Option ('Text 1', 'Value1'); ' – ruffin