I have an ASP drop down list called and I need to load numbers 1 to 20 with 1 being selected as default. How to do this with javascript? I have a sample code but the drop down is not loading. Am I missing something?
<script>
function quantitydropdown() {
var ddl = document.getElementById('quantitydropdownid').getElementsByTagName("select")[0];
for (var i = 1; i <= 100; i++) {
var theOption = new Option;
theOption.text = i;
theOption.value = i;
ddl.options[i] = theOption;
}
}
</script>
<select id="quantitydropdownid" onchange="javascript:quantitydropdown();" runat="server" style="width: 200px;"></select>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
So, when the document is ready, we populate the drop down:
// Set up event handler for when document is ready
window.addEventListener("DOMContentLoaded", function(){
// Get reference to drop down
var ddl = document.getElementById('quantitydropdownid');
for (var i = 1; i < 21; i++) {
var theOption = document.createElement("option");
theOption.text = i;
theOption.value = i;
// If it is the first option, make it be selected
i === 1 ? theOption.selected = "selected" : "";
ddl.options[i] = theOption;
}
});
#quantitydropdownid { width:200px; }
<select id="quantitydropdownid" runat="server"></select>
Method 2
Please try with this code
-----------------------------------------
JS Code
----------------
$(document).ready(function(){
quantitydropdown();
})
function quantitydropdown()
{
for (var i = 1; i <= 20; i++)
{
$("#quantitydropdownid").append( $("<option></option>")
.attr("value", i)
.text(i)
);
}
}
Css Code
-----------
#quantitydropdownid { width:200px; }
HTML Code
-----------
<select id="quantitydropdownid" runat="server"></select>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0