2

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);
    }
}
3
  • 1
    are you sure your function is getting executed? Commented Aug 9, 2013 at 22:09
  • @Matthew I updated the source path and yes it is executing the JS function Commented Aug 9, 2013 at 22:23
  • Try changing el.textContent = opt; to el.text = opt; Option elements have a special text property that is different from the newer textContent property of other elements. Your browser might require that. Commented Aug 9, 2013 at 23:10

1 Answer 1

6

Do you mean window.onload ?

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

Sign up to request clarification or add additional context in comments.

2 Comments

I see the dropdown list with 5 options when I expand and hover over options. But they are all null. I Dont see 1 through 5 numbers in the list just 5 empty slots
It looks ok here on Chrome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.