使用javascript从列表中获取项目的价值

时间:2012-04-10 13:13:22

标签: javascript

我有这段代码:

<script>
  function getgroup(){

        var i=0;
        var total=document.getElementById("selectedOptions").length;

    while (i<total)
  {
    var group=document.getElementById("selectedOptions").value;
    var group2=group.substring(2);

    alert(group2);
     i++;
}
}
</Script>

我想在列表中循环并获取列表中每个项目的值。 通过使用此代码,我只获得第一项的值。

请帮忙吗?

2 个答案:

答案 0 :(得分:2)

我认为您正在使用getElementById()方法,并且通过规范,元素的ID应该是唯一的,因此长度始终为1。尝试添加一个类并使用getElementsByClass()

答案 1 :(得分:1)

您正在将select元素的值分配给组变量。您需要循环使用选项:

group = document.getElementById("selectedOptions").options[i].value;