Search A Table With JavaScript

Using server side scripts to search for things can be as complex or as simple as the situation requires. However, if you have a table of results and you just want to enable a simple JavaScript search on that table then this might be the script for you.

To search a table using JavaScript you need to split the table into bits, this can be done using the getElementsByTagName() function, which takes the name of the element that you want to capture. So to grab all of the rows of a table as an array you need to pass the value of tr.

var rows = document.getElementsByTagName("tr");

We can then iterate through these rows, grabbing the column that you want to search on, with the following code.

for ( var i = 0; i < rows.length; i++ ) {
  var fullname = rows[i].getElementsByTagName("td");
  fullname = fullname[0].innerHTML.toLowerCase();
}

Before we can go any further we need a form so that the user can enter information and a table that can be used to search. First the form, the action of the input box will cause a function called doSearch() to be run, this will contain our search code.

<form action="#" method="get" onsubmit="return false;">
<input type="text" size="30" name="q" id="q" value="" onkeyup="doSearch();" />
</form>

Next, the table. Note that I have added an additional row to the end of this table. This will be used to display a note to the user if they have entered a query that isn't found.

<table>
<tr><td>One</td></tr>
<tr><td>Two</td></tr>
<tr><td>Three</td></tr>
<tr><td>Four</td></tr>
<tr><td>Five</td></tr>
<tr><td>Six</td></tr>
<tr><td>Seven</td></tr>
<tr><td>Eight</td></tr>
<tr style="display:none;" id="noresults"> 
 <td>(no listings that start with "<span id="qt"></span>")</td> 
</tr>
</table>

The first thing we need to do in our search function is to prepare the search term. This turns the query string to lowercase, which we can then match to the table column.

var q = document.getElementById("q");
var v = q.value.toLowerCase();

Now we can go through each row value and try to match it to the value in the query string. If it matches then we display the row, if not then we hide it.

for ( var i = 0; i < rows.length; i++ ) {
    var fullname = rows[i].getElementsByTagName("td");
    fullname = fullname[0].innerHTML.toLowerCase();
    if ( fullname ) {
        if ( v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1 ) ) {
        rows[i].style.display = "";
      } else {
        rows[i].style.display = "none";
      }
    }
  }

Here is the full function, including the code to implement the no results note.

<script type="text/javascript">
//<!--
function doSearch() {
  var q = document.getElementById("q");
  var v = q.value.toLowerCase();
  var rows = document.getElementsByTagName("tr");
  var on = 0;
  for ( var i = 0; i < rows.length; i++ ) {
    var fullname = rows[i].getElementsByTagName("td");
    fullname = fullname[0].innerHTML.toLowerCase();
    if ( fullname ) {
        if ( v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1 ) ) {
        rows[i].style.display = "";
        on++;
      } else {
        rows[i].style.display = "none";
      }
    }
  }
  var n = document.getElementById("noresults");
  if ( on == 0 && n ) {
    n.style.display = "";
    document.getElementById("qt").innerHTML = q.value;
  } else {
    n.style.display = "none";
  }
}
//-->
</script>

 

Comments

Is there a way to exclude certain rows. What If I had a header row above "One, Two, Three" that was called "Category". Can I exclude that and have it always appear?
Permalink
Sure, doing that is quite easy, and doesn't require much change. Just after the for loop that searches each column add the following code:
rows[0].style.display = "";
This will force the first row of the table to be displayed.
Name
Philip Norton
Permalink

I just improve slightly of the code

The function doSearch will require two parameter which is tableId and queryId

   function doSearch( tableId, queryId) {
       var q       = document.getElementById(queryId);
       var v       = q.value.toLowerCase();

       var t       = document.getElementById(tableId);
       var rows    = t.getElementsByTagName("tr");
       var on      = 0;

...rest will be the same

Permalink
<?php
       
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //to fully log out a visitor we need to clear the session varialbles
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
	
  $logoutGoTo = "logout.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?> </code></p>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="style.css" rel="stylesheet" />
<style type="text/css">#thead {
	color: #BBC2C6;
}
</style>
<script type='text/javascript'>
var $rows = $('#table tr');

function doSearch() {
    var q = document.getElementById("q");
    var v = q.value.toLowerCase();
    var rows = document.getElementsByTagName("tr");
    var on = 0;
    for ( var i = 0; i < rows.length; i++ ) {
        var fullname = rows[i].getElementsByTagName("td");
        fullname = fullname[0].innerHTML.toLowerCase();
        if ( fullname ) {
            if ( v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1 ) ) {
                rows[i].style.display = "";
                on++;
            } else {
                rows[i].style.display = "none";
            }
        }
    }
    var n = document.getElementById("noresults");
    if ( on == 0 && n ) {
        n.style.display = "";
        document.getElementById("qt").innerHTML = q.value;
    } else {
        n.style.display = "none";
    }
}
</script>
<p>&nbsp;
<div align="justify">
<div align="right"><code class="php"><a href="<?php echo $logoutAction ?>">Log out</a> </code></div>

<div id="container">&nbsp;</div>

<div id="header">
<h1><code class="php"><a href="http://www.skylinerestoration.com/"><img alt="" src="http://www.skylinerestoration.com/Skyline_Restoration/home_files/shapeimage_15.png" /></a> </code></h1>

<h2><code class="php">&nbsp;</code></h2>

<h2><code class="php"><span style="font-weight: normal;">11-20 37th Avenue, Long Island City, NY 11101</span></code></h2>

<h2 style="font-weight: normal;"><code class="php"><span style="font-weight: bold;">T</span>: &nbsp; <span style="font-weight: bold;">F</span>: </code></h2>
</div>

<form action="#" method="get" onsubmit="return false;"><code class="php"><input id="q" name="q" onkeyup="doSearch();" size="30" type="text" value="" /> </code></form>
&nbsp;

<table border="0" cellpadding="0" cellspacing="0" class="sortable" id="table">
	<thead>
		<tr>
			<th width="46">
			<h3><code class="php">ID</code></h3>
			</th>
			<th class="nosort" width="185">
			<h3><code class="php">Name</code></h3>
			</th>
			<th class="nosort" width="58">
			<h3><code class="php">Ext.</code></h3>
			</th>
			<th class="nosort" width="142">
			<h3><code class="php">Phone</code></h3>
			</th>
			<th class="nosort" width="281">
			<h3><code class="php">Email</code></h3>
			</th>
		</tr>
	</thead>
	<tbody id="data">
		<tr>
			<td><code class="php">1</code></td>
			<td>&nbsp;</td>
			<td>&nbsp;</td>
			<td>&nbsp;</td>
			<td>&nbsp;</td>
		</tr>
		<tr>
			<td><code class="php">2</code></td>
			<td>&nbsp;</td>
			<td>&nbsp;</td>
			<td>&nbsp;</td>
			<td>&nbsp;</td>
		</tr>
	</tbody>
</table>

<table border="0" cellpadding="0" cellspacing="0" class="sortable" height="62" id="table">
	<tbody>
		<tr>
			<td width="321">
			<div align="center">
			<h3><code class="php"><strong>IT Support</strong></code></h3>
			</div>
			</td>
			<td width="273">
			<h3 align="center"><code class="php"><strong>24/7 Emergency Helpline: </strong></code></h3>

			<h3 align="center">&nbsp;</h3>
			</td>
			<td width="385">
			<h3>&nbsp;</h3>
			</td>
		</tr>
	</tbody>
</table>

<div id="controls">
<div id="perpage"><code class="php"><select onchange="sorter.size(this.value)"><option value="5">5</option><option selected="selected" value="10">10</option><option value="20">20</option><option value="50">50</option><option value="100">100</option> </select> <span>Entries Per Page</span> </code></div>

<div id="navigation"><code class="php"><img alt="First Page" height="16" onclick="sorter.move(-1,true)" src="images/first.gif" width="16" /> <img alt="First Page" height="16" onclick="sorter.move(-1)" src="images/previous.gif" width="16" /> <img alt="First Page" height="16" onclick="sorter.move(1)" src="images/next.gif" width="16" /> <img alt="Last Page" height="16" onclick="sorter.move(1,true)" src="images/last.gif" width="16" /> </code></div>

<div id="text"><code class="php">Displaying Page of </code></div>
</div>
<code class="php"><script type="text/javascript" src="_script.js"></script>
<script type="text/javascript">
  var sorter = new directory.table.sorter("sorter");
	sorter.head = "head";
	sorter.asc = "asc";
	sorter.desc = "desc";
	sorter.even = "evenrow";
	sorter.odd = "oddrow";
	sorter.evensel = "evenselected";
	sorter.oddsel = "oddselected";
	sorter.paginate = true;
	sorter.currentid = "currentpage";
	sorter.limitid = "pagelimit";
	sorter.init("table",1);
  </script> </code>

<div id="footer"><code class="php"><a href="" target="_blank"><img alt="" height="209" onclick="" src="images/footer.png" width="983" /></a>

 

Permalink
in the example, when i type "a,s,d" quickly, the (no listings that start with "asd") dissapears and the table becomes empty. why does this happen and how do i fix this?
Permalink
The code is designed to hide anything that doesn't match the required criteria. So if you enter a term that it's in the table the table will be hidden.
Name
Philip Norton
Permalink
Hi ... Is there a way to search only coloum 2? It search in coloum 1 and i need coloum 2. Thanks
Permalink
Hi @ philipnorton42 the above code implements search only for the First element of the ROW if the row has more than one column it does not search the other values
Permalink

Hi, thanks for this great code. Is there a way to find results NOT equal to the search term.

For instance if I type "Boston" in the the search box, it will find all rows with Boston. But if I put an exclamation mark in front of Boston, "!Boston" , it will find everything except Boston. Or better still, two boxes, one for include and one for exclude. So searching for Boston would return:

Boston-Brookline

Boston-Dorchester

Boston-Southie

And then typing Southie in the exclude box would eliminate Boston-Southie from the results.

thanks very much in advance.

Permalink

Hi Roger,

Yes, you should be able to do that by swapping the display:none attribute. For example, swap this:

       if ( v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1 ) ) {
        rows[i].style.display = "";
      } else {
        rows[i].style.display = "none";
      }

To this:

       if ( v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1 ) ) {
        rows[i].style.display = "none";
      } else {
        rows[i].style.display = "";
      }

That should hide anything that doesn't match in the list.

Name
Philip Norton
Permalink

Why does the script not work when the table contains header <th> rows?

Permalink

It's not something I thought about when I wrote this script back in 2009. It was 14 years ago and I've learnt a lot since then.

You think it's worth having anther bash at it?

Name
Philip Norton
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
4 + 10 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.