Search ListBox items using JavaScript


This example shows how to select ListItems in the ListBox based from the TextBox values using JavaScript.

Here’s the code block below.

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >

<head id=”Head1″ runat=”server”>

<title>Demo</title>

</head>

<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].text.toLowerCase().match(tb.value.toLowerCase()))

{

l.options[i].selected = true;

return false;

}

else

{

ClearSelection(l);

}

}

}

}

function ClearSelection(lb)

{

lb.selectedIndex = -1;

}

</script>

<body>

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

</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.

See the output below when you run it on the page

Advertisements
This entry was posted in Asp.Net, C# and tagged , . Bookmark the permalink.

One Response to Search ListBox items using JavaScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s