user793468
user793468

Reputation: 4966

Populate select list using javascript

I am trying to populate HTML select list using JavaScript. I believe I am doing it correctly, but I am not able to populate the list. The list is still empty. What am I missing here?

HTML:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!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 runat="server">
<script type="text/javascript" src="../../Scripts/app/Base.js"></script>
    <title>Index</title>
</head>

<body>
    <div>
    Select <select id = "MyList"></select>
    </div>
</body>
</html>

JS:

window.onload = function(){
    var select = document.getElementById("MyList");
    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);
    }
}

Upvotes: 2

Views: 9299

Answers (1)

user2625787
user2625787

Reputation:

Do you mean window.onload ?

Fiddle: http://jsfiddle.net/5Jr8N/

Upvotes: 6

Related Questions