आप इसे एक सरल 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 , दोनों मेरे और Sime Vidas के उत्तर की पूर्ण तुलना करते हैं , क्योंकि मुझे लगा कि उनका विचार मेरी तुलना में थोड़ा अधिक समझने योग्य / सहज है और मैंने सोचा कि यह कैसे कार्यान्वयन में परिवर्तित होगा। क्रोमियम 14 / उबंटू 11.04 के अनुसार मेरा कुछ और तेज है, अन्य ब्राउज़रों / प्लेटफार्मों में हालांकि अलग-अलग परिणाम होने की संभावना है।
ओपी की टिप्पणी के जवाब में संपादित :
[कैसे] [I] इसे एक से अधिक तत्वों पर लागू करते हैं?
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);
जेएस फिडेल डेमो ।
और, आखिरकार (काफी देरी के बाद ...), एक विधि के रूप HTMLSelectElementमें populate()फंक्शन को चेन करने के लिए प्रोटोटाइप का विस्तार करने वाला एक तरीका, 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
});
जेएस फिडेल डेमो ।
संदर्भ: