Normally you have a requirement that user want to search or filtering record in a list box according to what he write in textbox.So in my pervious posted Search ListBox items using JavaScript.I explained how to search in listbox but there is one restriction when user want to search, it will select only one record and user can not see the other records related to searching criteria.So in this post I explain how to implement this thing if you have that kind or requirement.
First you write JavaScript code on html page.
<script type="text/javascript" language="javascript">
var ddlText, ddlValue, ddl, lblMesg;
function CacheItems() {
ddlText = new Array();
ddlValue = new Array();
ddl = document.getElementById("<%=ListBox1.ClientID %>");
lblMesg = document.getElementById("<%=lblMessage.ClientID%>");
for (var i = 0; i < ddl.options.length; i++) {
ddlText[ddlText.length] = ddl.options[i].text;
ddlValue[ddlValue.length] = ddl.options[i].value;
}
}
window.onload = CacheItems;
function FilterItems(value) {
ddl.options.length = 0;
for (var i = 0; i < ddlText.length; i++) {
if (ddlText[i].toLowerCase().indexOf(value) != -1) {
AddItem(ddlText[i], ddlValue[i]);
}
}
lblMesg.innerHTML = ddl.options.length + " items found.";
if (ddl.options.length == 0) {
AddItem("No items found.", "");
}
}
function AddItem(text, value) {
var opt = document.createElement("option");
opt.text = text;
opt.value = value;
ddl.options.add(opt);
}
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" onkeyup="FilterItems(this.value)"><br />
<asp:ListBox ID="ListBox1" runat="server" Height="150px" Width="250px">
<asp:ListItem>Vincent</asp:ListItem>
<asp:ListItem>Jennifer</asp:ListItem>
<asp:ListItem>Shynne</asp:ListItem>
<asp:ListItem>Christian</asp:ListItem>
<asp:ListItem>Helen</asp:ListItem>
<asp:ListItem>Vladi</asp:ListItem>
<asp:ListItem>Bee</asp:ListItem>
<asp:ListItem>Jerome</asp:ListItem>
<asp:ListItem>Vinz</asp:ListItem>
<asp:ListItem>Churchill</asp:ListItem>
<asp:ListItem>Rod</asp:ListItem>
<asp:ListItem>Mark</asp:ListItem>
</asp:ListBox>
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
</form>
</body>
</html>
The JavaScript function basically searches the ListBox items and find the items based from the value of the TextBox that was entered. If a keyword exist from the list then it will
automatically select the ListItems in the ListBox, but if the keyword does not exist then it will clear the ListBox selection.While the label will display the status message to the user