Search A Table With JavaScript

10th March 2009

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.

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

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.

  1. <form action="#" method="get" onsubmit="return false;">
  2. <input type="text" size="30" name="q" id="q" value="" onkeyup="doSearch();" />
  3. </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.

  1. <table>
  2. <tr><td>One</td></tr>
  3. <tr><td>Two</td></tr>
  4. <tr><td>Three</td></tr>
  5. <tr><td>Four</td></tr>
  6. <tr><td>Five</td></tr>
  7. <tr><td>Six</td></tr>
  8. <tr><td>Seven</td></tr>
  9. <tr><td>Eight</td></tr>
  10. <tr style="display:none;" id="noresults">
  11. <td>(no listings that start with "<span id="qt"></span>")</td>
  12. </tr>
  13. </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.

  1. var q = document.getElementById("q");
  2. 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.

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

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

  1. <script type="text/javascript">
  2. //<!--
  3. function doSearch() {
  4. var q = document.getElementById("q");
  5. var v = q.value.toLowerCase();
  6. var rows = document.getElementsByTagName("tr");
  7. var on = 0;
  8. for ( var i = 0; i < rows.length; i++ ) {
  9. var fullname = rows[i].getElementsByTagName("td");
  10. fullname = fullname[0].innerHTML.toLowerCase();
  11. if ( fullname ) {
  12. if ( v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1 ) ) {
  13. rows[i].style.display = "";
  14. on++;
  15. } else {
  16. rows[i].style.display = "none";
  17. }
  18. }
  19. }
  20. var n = document.getElementById("noresults");
  21. if ( on == 0 && n ) {
  22. n.style.display = "";
  23. document.getElementById("qt").innerHTML = q.value;
  24. } else {
  25. n.style.display = "none";
  26. }
  27. }
  28. //-->
  29. </script>

 

Comments

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

alfred smith (Thu, 04/16/2009 - 16:09)

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.

philipnorton42 (Fri, 04/17/2009 - 07:52)

Permalink

I just improve slightly of the code

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

  1. function doSearch( tableId, queryId) {
  2. var q = document.getElementById(queryId);
  3. var v = q.value.toLowerCase();
  4.  
  5. var t = document.getElementById(tableId);
  6. var rows = t.getElementsByTagName("tr");
  7. var on = 0;

...rest will be the same

asipo (Sun, 03/06/2011 - 08:56)

Permalink
  1. <?php //initialize the session
  2. if (!isset($_SESSION)) {
  3. }
  4.  
  5. // ** Logout the current user. **
  6. $logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
  7. if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  8. $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
  9. }
  10.  
  11. if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  12. //to fully log out a visitor we need to clear the session varialbles
  13. $_SESSION['MM_Username'] = NULL;
  14. $_SESSION['MM_UserGroup'] = NULL;
  15. $_SESSION['PrevUrl'] = NULL;
  16. unset($_SESSION['MM_Username']);
  17. unset($_SESSION['MM_UserGroup']);
  18. unset($_SESSION['PrevUrl']);
  19.  
  20. $logoutGoTo = "logout.php";
  21. if ($logoutGoTo) {
  22. header("Location: $logoutGoTo");
  23. }
  24. }
  25. ??><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>directoryTable</title><link rel="stylesheet" href="style.css" /><style type="text/css">
  26. <!--/*--><![CDATA[/* ><!--*/
  27.  
  28. #thead {
  29. color: #BBC2C6;
  30. }
  31.  
  32. /*--><!]]>*/
  33. </style><script type="text/javascript">
  34. <!--//--><![CDATA[// ><!--
  35.  
  36. var $rows = $('#table tr');
  37.  
  38. function doSearch() {
  39. var q = document.getElementById("q");
  40. var v = q.value.toLowerCase();
  41. var rows = document.getElementsByTagName("tr");
  42. var on = 0;
  43. for ( var i = 0; i < rows.length; i++ ) {
  44. var fullname = rows[i].getElementsByTagName("td");
  45. fullname = fullname[0].innerHTML.toLowerCase();
  46. if ( fullname ) {
  47. if ( v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1 ) ) {
  48. rows[i].style.display = "";
  49. on++;
  50. } else {
  51. rows[i].style.display = "none";
  52. }
  53. }
  54. }
  55. var n = document.getElementById("noresults");
  56. if ( on == 0 && n ) {
  57. n.style.display = "";
  58. document.getElementById("qt").innerHTML = q.value;
  59. } else {
  60. n.style.display = "none";
  61. }
  62. }
  63.  
  64. //--><!]]>
  65. </script><div align="justify">
  66. <div align="right"><a href="<?php echo $logoutAction ?>"> Log out</a>
  67. </div>
  68. <div id="container">
  69. </div>
  70. <div id="header">
  71.  
  72. <h1> <a href="http://www.skylinerestoration.com/"><img src="http://www.skylinerestoration.com/Skyline_Restoration/home_files/shapeimage_15.png" alt="" /></a> </h1>
  73. <h2> </h2>
  74. <h2><span style="font-weight: normal;">11-20 37th Avenue, Long Island City, NY 11101</span></h2>
  75. <h2 style="font-weight: normal;"><span style="font-weight: bold;">T</span>:   <span style="font-weight: bold;">F</span>:
  76. </h2>
  77.  
  78. </div>
  79.  
  80. <form action="#" method="get" onsubmit="return false;">
  81. <input type="text" size="30" name="q" id="q" value="" onkeyup="doSearch();" /></form>
  82.  
  83. <table cellpadding="0" cellspacing="0" border="0" id="table" class="sortable"><thead><tr><th width="46"><h3>ID</h3></th>
  84. <th width="185" class="nosort"><h3>Name</h3></th>
  85. <th width="58" class="nosort"><h3>Ext.</h3></th>
  86. <th width="142" class="nosort"><h3>Phone</h3></th>
  87. <th width="281" class="nosort"><h3>Email</h3></th>
  88. </tr></thead><tbody id="data"><tr><td>1</td>
  89. <td><strong></strong></td>
  90. <td><strong></strong></td>
  91. <td></td>
  92. <td></td>
  93. </tr><tr><td>2</td>
  94. <td><strong></strong></td>
  95. <td></td>
  96. <td></td>
  97. <td></td>
  98.  
  99. </tr></tbody></table><thead><table height="62" border="0" cellpadding="0" cellspacing="0" class="sortable" id="table"><tr><td width="321"><div align="center">
  100. <h3><strong>IT Support</strong></h3>
  101. </div></td>
  102. <td width="273"><h3 align="center"><strong>24/7 Emergency Helpline: </strong></h3>
  103. <h3 align="center"><strong></strong></h3></td>
  104. <td width="385"><h3></h3></td>
  105. </tr></table></thead><div id="controls">
  106. <div id="perpage">
  107. <select onchange="sorter.size(this.value)"><option value="5">5</option><option value="10" selected="selected">10</option><option value="20">20</option><option value="50">50</option><option value="100">100</option></select><span>Entries Per Page</span>
  108. </div>
  109. <div id="navigation">
  110. <img src="images/first.gif" width="16" height="16" alt="First Page" onclick="sorter.move(-1,true)" /><img src="images/previous.gif" width="16" height="16" alt="First Page" onclick="sorter.move(-1)" /><img src="images/next.gif" width="16" height="16" alt="First Page" onclick="sorter.move(1)" /><img src="images/last.gif" width="16" height="16" alt="Last Page" onclick="sorter.move(1,true)" /></div>
  111. <div id="text">Displaying Page <span id="currentpage"></span> of <span id="pagelimit"></span></div>
  112.  
  113. </div>
  114. <!-- <script type="text/javascript" src="_script.js"></script>
  115. <script type="text/javascript">
  116. var sorter = new directory.table.sorter("sorter");
  117. sorter.head = "head";
  118. sorter.asc = "asc";
  119. sorter.desc = "desc";
  120. sorter.even = "evenrow";
  121. sorter.odd = "oddrow";
  122. sorter.evensel = "evenselected";
  123. sorter.oddsel = "oddselected";
  124. sorter.paginate = true;
  125. sorter.currentid = "currentpage";
  126. sorter.limitid = "pagelimit";
  127. sorter.init("table",1);
  128. </script>-->
  129.  
  130.  
  131. <div id="footer"><a href="" target="_blank"><img src="images/footer.png" alt="" width="983" height="209" onclick="" /></a> </div>
  132.  
  133. </div>

Andro (Sun, 09/02/2012 - 04:12)

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?

emma (Fri, 01/18/2013 - 06:39)

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.

philipnorton42 (Fri, 01/18/2013 - 09:04)

Permalink
Hi ... Is there a way to search only coloum 2? It search in coloum 1 and i need coloum 2. Thanks

Marco (Sun, 08/02/2015 - 18:57)

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

shubham (Wed, 10/26/2016 - 10:28)

Add new comment

The content of this field is kept private and will not be shown publicly.