最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Populate select list using javascript - Stack Overflow

programmeradmin4浏览0评论

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; 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. – user2625787 Commented Aug 9, 2013 at 23:10
Add a ment  | 

1 Answer 1

Reset to default 6

Do you mean window.onload ?

Fiddle: http://jsfiddle/5Jr8N/

发布评论

评论列表(0)

  1. 暂无评论