Searching in a list with Javascript

Friday, September 10, 2010

In this tutorial I will show you how to create a script what searches in a list (li or table) for the inputted text at each press of a button. Because I can`t explain better what the script can do, here is an example:

How it works:
The script loops through all the 'li' elements from the document and searches for the ones with class "search". From these 'li' elements it resizes to 0 pixels the ones what don`t contain the searched word, and it resizes to its original size the ones what contain the searched word:
<html>
<head>

<style>
.search {
overflow:hidden;
}
</style>

</head>
<body>

<input type="text" id="searchbar" onKeyUp="searchit();"/>
<ul style="list-style:none;margin:0px;padding:0 15px;">
<li class="search">Coffee</li>
<li class="search">Milk</li>
<li class="search">Chees</li>
<li class="search">Tea</li>
<li class="search">Orange</li>
<li class="search">Sugar</li>
<li class="search">Honey</li>
<li class="search">Milkshake</li>
</ul>

<script type="text/javascript">
function searchit(){
var keyword = document.getElementById('searchbar').value;
for(var i=0;i<document.getElementsByTagName('li').length;i++){
if(document.getElementsByTagName('li')[i].className == 'search'){
if(document.getElementsByTagName('li')[i].innerHTML.toLowerCase().indexOf(keyword.toLowerCase()) == -1){
document.getElementsByTagName('li')[i].style.height = '0px';
}
else{
document.getElementsByTagName('li')[i].style.height = '20px';
}
}
}
}
</script>

</body>
</html>
Note: The list must have the overflow:hidden; property!

3 comments:

Is there anyway to hide the li elements? So that the user does not see the choices, however, once they type a keyword, the li elements appear?

include the following code after the first line of the searchit() function (var keyword = document.getElementById('searchbar').value;):

if(keyword == "" || keyword == " "){
document.getElementById('list').style.visibility = 'hidden';
}
else{
document.getElementById('list').style.visibility = 'visible';
}

and change <ul style="list-style:none;margin:0px;padding:0 15px;">

into this:

<ul style="list-style:none;margin:0px;padding:0 15px;visibility:hidden;" id="list">

Is it possible to search from a textarea or input field ??

Post a Comment