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" ".dtd">
<html xmlns="" >
<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);
}
}
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/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3/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);
}
}
Share
Improve this question
edited Aug 9, 2013 at 22:22
user793468
asked Aug 9, 2013 at 22:07
user793468user793468
4,97624 gold badges84 silver badges126 bronze badges
3
- 1 are you sure your function is getting executed? – Matthew Commented Aug 9, 2013 at 22:09
- @Matthew I updated the source path and yes it is executing the JS function – user793468 Commented Aug 9, 2013 at 22:23
-
Try changing
el.textContent = opt;
toel.text = opt;
Option elements have a specialtext
property that is different from the newertextContent
property of other elements. Your browser might require that. – user2625787 Commented Aug 9, 2013 at 23:10
1 Answer
Reset to default 6Do you mean window.onload
?
Fiddle: http://jsfiddle/5Jr8N/