繁体   English   中英

如何使用JavaScript获取ListBox中每个ListItem的值

[英]How do I get the value of each ListItem in a ListBox using JavaScript

我有一个动态填充的列表框。 如果ListItem的值与特定的字符串匹配,我想将每个选定的ListItem标记为“选定”。

ASP.NET:

<asp:ListBox ID="lstComputers" runat="server"></asp:ListBox>

C#:

//code that populates lstComputers.
//I got this part working properly already

使用Javascript:

//I'm really bad at javascript, so here's the sudo code of what I'd like done
For each ListItem in lstComputers{
  If ListItem.value like 'HP%' then{  //assuming % is like a wild card in SQL
    ListItem.selected = true;
  }
}

请帮助我使用JavaScript。

谢谢

尝试这个:-

function SelectListBox() {
        var lstComputers = document.getElementById("<%= lstComputers.ClientID %>");
        for (var i = 0; i < lstComputers.options.length; i++) {
            if (lstComputers.options[i].text.indexOf("HP") > -1) {
                lstComputers.options[i].selected = true;
            }
        }
    }

另外,如果要在ListBox控件中进行多重选择,请确保将SelectionMode属性设置为Multiple

Asp.net ListBox将生成Select Tag的html,我们可以使用jQuery轻松访问javascript中的select元素及其选项。

以下是将完成您的工作的Javascript代码。

<script>   
 $("#lstComputers option").each(function(){

      var option = $(this);
    if(option.text().indexOf('HP') == 0)
    {
      option.attr('selected','selected');
    }

    });

</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM