[英]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.