Search code examples
javascripthtmlhtml-selectappendchild

Populating dropdown list from array working on JSFiddle but not working on local machine?


Hey everyone I am trying to populate dropdown list with array but it is not working but is working fine when I use the same code on JSFiddle. Please help

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery-1.9.1.js">
</script>
<script type="text/javascript">

var select = document.getElementById("selectNumber");
var options = ["1", "2", "3", "4", "5"];
for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}
</script>
</head>

<body>

<select id="selectNumber">
    <option>Choose a number</option>
</select>
</body>
</html>

When I use alert boxes like given below

var select = document.getElementById("selectNumber");
var options = ["1", "2", "3", "4", "5"];
for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    alert();
    select.appendChild(el);
    alert();
}

The first alert box appears but the second alert box does not appear ie only first iteration of loop is running which terminates at select.appendChild(el);.


Solution

  • Put your JavaScript code in document.ready function like this :

    <script type="text/javascript">
    $(document).ready(function() {
    var select = document.getElementById("selectNumber");
    var options = ["1", "2", "3", "4", "5"];
    for(var i = 0; i < options.length; i++) {
        var opt = options[i];
        var el = document.createElement("option");
        el.textContent = opt;
        el.value = opt;
        select.appendChild(el);
    }
    });
    </script>
    

    Your values were not appending because the DOM was initialized after the script was executed. It is a good practice to put your code in document.ready function.