简体   繁体   中英

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

I have a ListBox that's dynamically populated. I'd like to mark each selected ListItem as "selected" if the value of the ListItem matches a specific string of characters.

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;
  }
}

Please help me out with the JavaScript.

Thanks

Try this:-

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;
            }
        }
    }

Also, Please make sure you have SelectionMode property set to Multiple if you want multiple selection in ListBox control.

The Asp.net ListBox will generate the html of Select Tag and we can access that select element and its option in javascript using jQuery easily.

Following is the Javascript code that will do your work.

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

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

    });

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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