This example shows how to select ListItems in the ListBox based from the TextBox values using JavaScript.
Here’s the code block below.
<script type="text/javascript" language="javascript">
function SearchList()
{
var l = document.getElementById('<%= ListBox1.ClientID %>');
var tb = document.getElementById('<%= TextBox1.ClientID %>');
if(tb.value == "")
{
ClearSelection(l);
}
else{
for (var i=0; i < l.options.length; i++)
{
if (l.options[i].value.toLowerCase().match(tb.value.toLowerCase()))
{
l.options[i].selected = true;
return false;
}
else
{
ClearSelection(l);
}
}
}
}
function ClearSelection(lb)
{
lb.selectedIndex = -1;
}
</script>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" onkeyup="return SearchList();"/><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>
|
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.
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.
See the output below when you run it on the page
No comments:
Post a Comment