Thursday, November 15, 2012

Javascript Search and Filter Table

The below code is not my own work.  I found it highly useful and beautifully coded, if you ever want to search for a keyword in a designated table and filter out the rest of the results.

I was able to take a piece of the code and add a refresh button.  I'll post that later when I get into work tomorrow.



<script language="javascript" type="text/javascript">
       //define the table search as an object, which can implement both functions and properties
       window.tableSearch = {};

       //initialize the search, setup the current object
       tableSearch.init = function() {
           //define the properties I want on the tableSearch object
           this.Rows = document.getElementById('data').getElementsByTagName('TR');
           this.RowsLength = tableSearch.Rows.length;
           this.RowsText = [];
           
           //loop through the table and add the data to
           for (var i = 0; i < tableSearch.RowsLength; i++) {
               this.RowsText[i] = (tableSearch.Rows[i].innerText) ? tableSearch.Rows[i].innerText.toUpperCase() : tableSearch.Rows[i].textContent.toUpperCase();
           }
       }

       //onlys shows the relevant rows as determined by the search string
       tableSearch.runSearch = function() {
           //get the search term
           this.Term = document.getElementById('textBoxSearch').value.toUpperCase();
           
           //loop through the rows and hide rows that do not match the search query
           for (var i = 0, row; row = this.Rows[i], rowText = this.RowsText[i]; i++) {
               row.style.display = ((rowText.indexOf(this.Term) != -1) || this.Term === '') ? '' : 'none';
           }
       }

       //runs the search
       tableSearch.search = function(e) {
           //checks if the user pressed the enter key, and if they did then run the search
           var keycode;
           if (window.event) { keycode = window.event.keyCode; }
           else if (e) { keycode = e.which; }
           else { return false; }
           if (keycode == 13) {
               tableSearch.runSearch();
           }
           else { return false; }
       }
   </script>

//add this to the body tag
onload="tableSearch.init();"


//add this table anywhere
<table>
<tr>
<td><input type="text" size="30" maxlength="1000" value="" id="textBoxSearch" onkeyup="tableSearch.search(event);" />
                   <input type="button" value="Search" onclick="tableSearch.runSearch();" /></td>
</tr>
</table>


//make sure to give the table to search this name

id="data"

No comments:

Post a Comment