JavaScript Search

Last week, I encountered a need to be able to show search results based on a list on the web page, and I developed the following code to achieve it.

First of all I had a list with id “bever” –

<ul id="bever">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

The following is the JavaScript :

function search(q,e){
q = q.toLowerCase();
var key;
if (window.event){key = window.event.keyCode;}
else{key = e.which;}
if (key == 13){
var a = bever.getElementsByTagName('li');
document.getElementById('results').innerHTML = "<h3>Search Results :</h3><ul>"; // Clearing the previous contents of the Search Results holder and adding the relevant new stuff
var b = a.length; // Take the total number of resources to search in
var i;
for (i=0; i<b; i++){
var c = a[i].innerText;
c = c.toLowerCase();
if (c.indexOf(q) >= 0){
document.getElementById('results').innerHTML += "<li>" + c + "</li>";
}
}
document.getElementById('results').innerHTML += "</ul>";
}
}

The complete HTML would look like :

<!doctype html>
<html>
<head>
<script>
function search(q,e){
q = q.toLowerCase();
var key;
if (window.event){key = window.event.keyCode;}
else{key = e.which;}
if (key == 13){
var a = bever.getElementsByTagName('li');
document.getElementById('results').innerHTML = "<h3>Search Results :</h3><ul>"; // Clearing the previous contents of the Search Results holder and adding the relevant new stuff
var b = a.length; // Take the total number of resources to search in
var i;
for (i=0; i<b; i++){
var c = a[i].innerText;
c = c.toLowerCase();
if (c.indexOf(q) >= 0){
document.getElementById('results').innerHTML += "<li>" +
a[i].innerText
 + "</li>";
}
}
document.getElementById('results').innerHTML += "</ul>";
}
}
</script>
</head>
<body>
<label>Search For : </label><input type="text" onkeyup="search(this.value,event);" />
<div id="results" style="border:1px solid black;"></div>
<ul id="bever">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
</body
</html>

The above code will display the search results once you type in the keyword (or part of it) and press Enter. An instant search feature could be made by the following JavaScript. But, mind you, this could be take a little more time especially if the list is large.

function search(q,e){
q = q.toLowerCase();
var a = bever.getElementsByTagName('li');
document.getElementById('results').innerHTML = "<h3>Search Results :</h3><ul>";
var b = a.length; 
var i;
for (i=0; i<b; i++){
var c = a[i].innerText;
c = c.toLowerCase();
if (c.indexOf(q) >= 0){
document.getElementById('results').innerHTML += "<li>" + a[i].innerText + "</li>";
}
}
document.getElementById('results').innerHTML += "</ul>";
}
Advertisements