Akansha
Akansha

Reputation: 209

Load asp dropdown list with numbers 1 - 20

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>

Upvotes: 0

Views: 1764

Answers (2)

Kunal Patel
Kunal Patel

Reputation: 119

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>

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65883

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>

Upvotes: 2

Related Questions