19+ JavaScript Search Box for Table Example & Tutorial

JavaScript Search Box for Table
Code Snippet:Vanilla JS table filter
Author: Priyanka Malviya
Published: June 8, 2023
Last Updated: July 28, 2023
Downloads: 19,099
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create a search box for HTML table to filter table data. You can use this code to filter/search table data for multiple tables on a single page. It can be easily attached to your existing table by creating input (for search) with a data-table attribute.

It doesn’t matter how many rows and columns you have in your HTML table. This lightweight Vanilla JavaScript plugin searches through all rows/columns and displays the matched result.

How to Create JavaScript Search Box for Table

1. First of all, create an input element with a class name “table-filter” for the search box and create your table element with a class name “table”.

<section class="container cd-table-container">
  <h2 class="cd-title">Search Table Record:</h2>
  <input type="text" class="cd-search table-filter" data-table="order-table" placeholder="Item to filter.." />

  <table class="cd-table table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
        <th>ID</th>
      </tr>
    </thead>

    <tbody>
      <tr>
        <td>Your data goes here...</td>
        <td>Email goes here...</td>
        <td>Phone number goes here...</td>
        <td>ID goes here...</td>
      </tr>
        .
        .
        .
        .
        .
      <tr>
        <td>Your data goes here...</td>
        <td>Email goes here...</td>
        <td>Phone number goes here...</td>
        <td>ID goes here...</td>
      </tr>
    </tbody>
  </table>
</section>

2. If you want to create a search box for your existing HTML table, then you only need to create an input element. So, create the input and set the class name of your table to the "data-table" attribute.

  <input type="text" class="cd-search table-filter" data-table="your-table" placeholder="Item to filter.." />

3. Basically, the CSS styles are optional for the table. Anyhow, you can use the following CSS styles if you want to style the table.

.cd-table-container{
  background: #fff;
  box-shadow: 1px 2px 26px rgba(0, 0, 0, 0.2);
  padding: 15px;
  max-width: 720px;
}
/* Table Design */
.cd-table{
  width: 100%;
  color: #666;
  margin: 10px auto;
  border-collapse: collapse;
}

.cd-table tr,
.cd-table td{
  border: 1px solid #ccc;
  padding: 10px;
}
.cd-table th{
  background: #017721;
  color: #fff;
  padding: 10px;
}

/* Search Box */
.cd-search{
  padding: 10px;
  border: 1px solid #ccc;
  width: 100%;
  box-sizing: border-box;
}

/* Search Title */
.cd-title{
  color: #666;
  margin: 15px 0;
}

4. Finally, add the following JavaScript function into your project for table search filter and done.

(function() {
	'use strict';

var TableFilter = (function() {
 var Arr = Array.prototype;
		var input;
  
		function onInputEvent(e) {
			input = e.target;
			var table1 = document.getElementsByClassName(input.getAttribute('data-table'));
			Arr.forEach.call(table1, function(table) {
				Arr.forEach.call(table.tBodies, function(tbody) {
					Arr.forEach.call(tbody.rows, filter);
				});
			});
		}

		function filter(row) {
			var text = row.textContent.toLowerCase();
       //console.log(text);
      var val = input.value.toLowerCase();
      //console.log(val);
			row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
		}

		return {
			init: function() {
				var inputs = document.getElementsByClassName('table-filter');
				Arr.forEach.call(inputs, function(input) {
					input.oninput = onInputEvent;
				});
			}
		};
 
	})();

  /*console.log(document.readyState);
	document.addEventListener('readystatechange', function() {
		if (document.readyState === 'complete') {
      console.log(document.readyState);
			TableFilter.init();
		}
	}); */
  
 TableFilter.init(); 
})();

That’s all! hopefully, you successfully integrated this JavaScript search filter plugin into your project. If you have any questions or suggestions, let me know by comment below.

10 thoughts on “19+ JavaScript Search Box for Table Example & Tutorial”

  1. hi
    using your code (pasted below) can’t seem to get search to work
    i open in browser and table etc display very nicely but filter search does not work
    please advise
    thanks!

    .cd-table-container{
      background: #fff;
      box-shadow: 1px 2px 26px rgba(0, 0, 0, 0.2);
      padding: 15px;
      max-width: 720px;
    }
    /* Table Design */
    .cd-table{
      width: 100%;
      color: #666;
      margin: 10px auto;
      border-collapse: collapse;
    }
    
    .cd-table tr,
    .cd-table td{
      border: 1px solid #ccc;
      padding: 10px;
    }
    .cd-table th{
      background: #017721;
      color: #fff;
      padding: 10px;
    }
    
    /* Search Box */
    .cd-search{
      padding: 10px;
      border: 1px solid #ccc;
      width: 100%;
      box-sizing: border-box;
    }
    
    /* Search Title */
    .cd-title{
      color: #666;
      margin: 15px 0;
    }
    
    (function() {
    	'use strict';
    
    var TableFilter = (function() {
     var Arr = Array.prototype;
    		var input;
      
    		function onInputEvent(e) {
    			input = e.target;
    			var table1 = document.getElementsByClassName(input.getAttribute('data-table'));
    			Arr.forEach.call(table1, function(table) {
    				Arr.forEach.call(table.tBodies, function(tbody) {
    					Arr.forEach.call(tbody.rows, filter);
    				});
    			});
    		}
    
    		function filter(row) {
    			var text = row.textContent.toLowerCase();
           //console.log(text);
          var val = input.value.toLowerCase();
          //console.log(val);
    			row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
    		}
    
    		return {
    			init: function() {
    				var inputs = document.getElementsByClassName('table-filter');
    				Arr.forEach.call(inputs, function(input) {
    					input.oninput = onInputEvent;
    				});
    			}
    		};
     
    	})();
    
      /*console.log(document.readyState);
    	document.addEventListener('readystatechange', function() {
    		if (document.readyState === 'complete') {
          console.log(document.readyState);
    			TableFilter.init();
    		}
    	}); */
      
     TableFilter.init(); 
    })();
    
    Reply
    • Hi David!
      Please make sure you properly followed the tutorial. Secondly, check console errors if something is going wrong.
      If you are still facing the problem, download the code snippet and edit the HTML file and add your table data into it.

      Reply
  2. hi
    1. your idea worked out. went over tutorial. now code works as should. fantastic
    2. how would I make following modification.
    3. table when first opened displays entire table.
    4. is there a way to pass a dummy “filter/search request” as part of INIT so that table displays not in its entirety?
    thanks!

    Reply
    • Hi David!
      Yes, it’s possible to pass a value in search input to show filtered data. To do this, follow the steps:
      1. Add a value attribute to the input element and define a unique id for this:

      <input id="tableSearchInput" value="asif" type="text" class="cd-search table-filter" data-table="order-table" placeholder="Item to filter.." />
      

      2. Add the following script just before the closing of the body tag:

       <script>
          var tableSearch = document.getElementById('tableSearchInput');
           
          if ("createEvent" in document) {
          var evt = document.createEvent("HTMLEvents");
          evt.initEvent("input", false, true);
          tableSearch.dispatchEvent(evt);
          }
          else {
           tableSearch.fireEvent("oninput");
          }
      </script>
      

      You can pass the keyword inside the value attribute, the table data will be filtered accordingly on load.

      Reply
  3. Hi
    great!
    1. so this new value attribute is instead of current or in addition to?
    if latter, place it right after current?
    2. currently before body tag is
    the new code can be part of this?
    thanks!
    PS
    can’t thank you enough. i am a former AS/400 RPG programmer getting my feet wet with html/css/js

    Reply
  4. Hi,
    Thanks so much for this; really helpful and improved what I had before! Please could you help me with a couple of things?
    I’d like to change the text in the search box to be darker/black etc. is that possible?
    Also when I search (it works perfectly to do so), I’d like to leave the top row of headings. I’ve tried adding a for loop but it didn’t work out. I’m quite new to html/js so learning as I go! Thanks 🙂

    Reply
  5. Hi,
    Thank you for this code, it has improved what I already had. Is it possible to change the font colour of the text in the search box – I’d like it more obvious? And is it possible to keep the headings of the columns when searching; at the moment they disappear.
    Thanks again
    Emma

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X