Puoi farlo con un semplice forciclo:
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);
}
Demo di JS Fiddle .
Il confronto tra JS Perf sia della mia e della risposta di Sime Vidas , eseguito perché pensavo che fosse un po 'più comprensibile / intuitivo della mia e mi chiedevo come ciò si sarebbe tradotto in implementazione. Secondo Chromium 14 / Ubuntu 11.04 la mia è un po 'più veloce, tuttavia altri browser / piattaforme avranno probabilmente risultati diversi.
Modificato in risposta al commento dell'OP:
[Come] [I] applicare questo a 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);
Demo di JS Fiddle .
E, infine (dopo un bel ritardo ...), un approccio che estende il prototipo di al HTMLSelectElementfine di concatenare la populate()funzione, 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
});
Demo di JS Fiddle .
Riferimenti: