< Back

Add Search to your HTML Grid with jQuery

Run the demo here.

Search is hard — just ask Google. It’s hard because it requires effort and expertise from many disciplines. Database gurus are needed to build an efficient indexable datastore. Developers are required to handle search queries and prepare query results for the UI. Finally, designers and usability experts need to figure out how best to communicate with users.

This post, although related to search generally, really just describes a simple on-page filtering process — and therefore is easy. Our goal is to take a HTML grid of user data and allow the user to show only the rows that match a particular name. We need three components to make it work, an input for our search query, a tabular HTML grid of user data and a javascript handler that will filter the grid data and update the UI.

So, let’s get started.

The Input Field

<label for="search-term">Search by Name</label>
<input type="text" id="search-term" />

Create an input control that jQuery will use to filter the grid.

The HTML Grid

<table id="userGrid">
		<td>John Smith</td>
		<td>Sally Sue</td>

Pretty simple html table. It should be noted that the jQuery search hook can be configured easily to work with table-less designs. Particularly, if each row’s columns are contained in a <div> or <span> element.

The Javascript

$(function() {
	grid = $('#userGrid');

	// handle search fields key up event
	$('#search-term').keyup(function(e) { 
		text = $(this).val(); // grab search term

		if(text.length > 1) {
			grid.find('tr:has(td)').hide(); // hide data rows, leave header row showing

			// iterate through all grid rows
			grid.find('tr').each(function(i) {
				// check to see if search term matches Name column
					$(this).show(); // show matching row
			grid.find('tr').show(); // if no matching name is found, show all rows

The comments should illustrate how the javascript works. Basically, every time a user enters a character into the search field, we run over each row of the grid looking for a matching name (or part of a name).

That’s all folks!

Connect with us

Thank You!

We really appreciate your interest in what we do.

We'll get back to you as soon as we can.