Javascript Table filter

This is a simple but powerful javascript to filter a standard html table. The user enters a term in a text field and just the table entries which contain it will be shown.
function filter (term, _id, cellNr){
	var suche = term.value.toLowerCase();
	var table = document.getElementById(_id);
	var ele;
	for (var r = 1; r < table.rows.length; r++){
		ele = table.rows[r].cells[cellNr].innerHTML.replace(/<[^>]+>/g,"");
		if (ele.toLowerCase().indexOf(suche)>=0 )
			table.rows[r].style.display = '';
		else table.rows[r].style.display = 'none';
	}
}
This function searches in the table with the id defined by _id in every row in the cell defined by cellNr. The search is case insensitive.
The usage is straightforward:
<form>
	<input name="filter" onkeyup="filter(this, 'sf', 1)" type="text">
</form>
It should work with all modern browsers, e.g. IE5, Firefox 1.0, Opera 7 and Mozilla 1.0.

Since many people have asked for another version of the script which
  • searches in every cell of a row
  • searches for more than one keyword (using AND)
I have made another version of the script:
function filter2 (phrase, _id){
	var words = phrase.value.toLowerCase().split(" ");
	var table = document.getElementById(_id);
	var ele;
	for (var r = 1; r < table.rows.length; r++){
		ele = table.rows[r].innerHTML.replace(/<[^>]+>/g,"");
	        var displayStyle = 'none';
	        for (var i = 0; i < words.length; i++) {
		    if (ele.toLowerCase().indexOf(words[i])>=0)
			displayStyle = '';
		    else {
			displayStyle = 'none';
			break;
		    }
	        }
		table.rows[r].style.display = displayStyle;
	}
}


Demo

Here is a little example (of the second script version), I just copied the result table from sourceforge after a search for the term "javascript".

Include:

Project Name Description Files Activity %
FCKeditor Online text editor (DHTML editor), for ASP, ASP.NET, ColdFusion, PHP, Java and JavaScript brings to the web many of the powerful functionalities of known desktop editors like Word. It's XHTML compliant and works with Firefox, Mozilla, Netscape and IE.  released files99.99%
TinyMCE TinyMCE is a platform independent webbased Javascript HTML WYSIWYG editor control, developed in JavaScript/ECMAScript and it's main features include theme/template support, language support and plugin extentions. Works in Mozilla, Firefox and MSIE  released files99.35%
ARSC Really Simple Chat ARSC is a webchat system that uses PHP and MySQL and allows comfortable chatting with every browser on the surface of this planet, using JavaScript, frames HTML streaming for modern browsers down to a one-page reload-yourself version for text browsers.  released files98.82%
Struts Menu Web menuing framework for JSP and Struts based applications. Menus can be defined in an XML file and displayed through the use of JSP tags. Support for dynamic javascript menus is included.  released files98.24%
IE7 IE7 is a library of JavaScript modules that provide a layer of W3C standards compatibility for Microsoft Internet Explorer 5+. IE7 supports CSS2/3 properties and selectors and fixes numerous rendering bugs.  released files97.84%
htmlArea WYSIWYG editor replacement for textarea formfields. Mozilla (any platform) and IE 5.5+ for Windows. Written in Javascript and works with any server-side software.  97.10%
WebChess A great persistant online chess game using PHP/MySQL on the backend and HTML/JavaScript on the front-end, which includes move validation, CHECK checking, pawn promotion and undo. It also has a login system which allows multiple simultaneous games.  released files96.38%
JavaScript Editor PlugIn for Eclipse The project is an Eclipse plugin that provides an editor for JavaScript files with syntax highlighting and outlining including some common OO approaches. Supported OO outline features are: Constructor, Class methods, Instance methods, Class variables etc  released files93.97%
PHP Layers Menu A DHTML menu system providing also accessibility (no-JavaScript) solutions.  released files93.96%
JPSpan JPSPAN provides tools to "hook up" PHP and Javascript, for the purpose of fetching data from PHP into a web page which has already loaded, without reloading the entire page. It allows you to call remote PHP objects as local Javascript objects  released files93.60%
SALWAlib - ASP Library SALWAlib is an ASP (Active Server Pages) library of functions an subroutines written in VBScript/JavaScript to help in the development of web sites suported by databases.  released files89.95%
xmenu/xlayer Xmenu is a versatile, javascript driven DHTML menu that works on most popular browsers. It comes in 3 basic modes: vertical, horizontal or collapsing and folds/unfolds on clicks or mouseovers. Easy to implement, it doesn't need any absolute coordinates.  released files89.61%
Obie Website Free PHP and Javascript website. Ad manager, Virtual inbox, referers checker, Counters ... etc... and many more.  released files89.43%
WebChat WebChat is an chat application for JavaScript compatible web browsers made in PHP. multiple rooms no browser flicker between message translation web based room management database backend private messages emotions and text formating multi  released files89.12%
JSDoc JSDoc is a documentation tool for Object-Oriented Javascript code, working in a similar fashion to Sun's JavaDoc for Java.  released files88.98%
ActiveWidgets Grid (Free Edition) The best free cross-browser scrolling datagrid control! Hand-made with 100% client-side JavaScript/DHTML, provides clean separation between data models, presentation templates and control behavior, plus professional look-and-feel and high interactivity.  released files87.92%
w3m w3m is a pager and/or text-based browser. It can handle table, cookies, authentication, and almost everything except JavaScript.   released files87.80%
FormattedDataSet API The FormattedDataSet Java API is the easiest way to generate dynamic text (HTML, XML, WML, JavaScript,...). The dynamic text is generated by using tabular data as input (SQL statements, ResultSets, 2 dimensional arrays,...).  released files87.00%
JWChat - Jabber Web Chat JWChat aims to be a full featured, web based jabber client. It uses only JavaScript and HTML on the client-side. Currently it supports basic jabber instant messaging, roster management and muc-based groupchats.  released files86.66%
OpenFlow OpenFlow is a web based, publishing workflow management system aimed at magazine production, controlling editorial planning thru imposition. It uses web standards (XHTML, CSS, javascript, XML, XSL, RDF) making it easy to configure and customize.  released files85.19%
Audiere Audio System Audiere is a portable audio library which supports playing MP3, Ogg Vorbis, FLAC, WAV, IT, XM, S3M, and MOD files. You can use it from C, C++, Python, Java, Delphi, and any language that supports XPCOM (JavaScript in Mozilla, for example).  released files83.65%
Shadows Rising RPG Shadows Rising is a browser based RPG written in PHP, Javascript, and XHTML. MySQL/PostgreSQL supported. The core engine will allow users create unique RPGs by adding new items, classes, terrain maps, etc. to Game Modules. Licensed under the Affero GPL.  released files83.24%
Morten's JavaScript Tree Menu Morten's JavaScript Tree Menu is a Windows Explorer(tm)-like hierarchial menu system for websites using JavaScript. Supports browsers from Netscape 3 onwards.  released files83.21%
Speller Pages Speller Pages is a Web interface and JavaScript library for a server-side spell check program. Available in PHP or Perl/CGI versions, Speller Pages allows you to bring the superior spelling suggestion capabilites of GNU Aspell to users of your Web site.  released files83.13%
xml for SCRIPT XML for SCRIPT is a powerful, standards-compliant JavaScript XML parser that is designed to help web application designers implement cross platform applications that take advantage of client-side manipulation of XML data.  released files82.84%

Small modification to have a "clear results" button that works

This is a great tool, but I think that others may find this small addition useful: A "clear filter" button

I added the following function

function resetfilter(_id) {
document.getElementById('filt').value = '';
var table = document.getElementById(_id);
for (var r = 1; r < table.rows.length; r++){
displayStyle = '';
table.rows[r].style.display = displayStyle;
}
}

And altered the HTML form to add a button that called the above with the table name.

Thank you very much for this.

Html

Hi,

I am a starter in JAVA script.

I like the script filterTable.js. That would be great if it works in my web application. I created the following HTML file based on your sample but the HTML file doesn't work.

.highlighted { background: yellow; }

Title 1
Title 2
Title 3

aaa1
bbb2
ccc3
ddd3

~
Something wrong?

thank you in advance!

Sumiko

I have no idea about

I have no idea about Javascript (i only know it exists), but I integrated your script with my needs in just two minutes.
Thank you very much. Perfect work!

speed up filter2 and row count

Hi!

Could you help me about speeding up the second version (my table contains about 4000 rows) with a submit button and a matches row count?
(I tried to use the version described in a comment at http://leparlement.org/filterTable, but cannot use it, because of this is an other version, and the filterTable.js is not working for me at all).

Thanks

Great! Is it possible to preload filter text from GET args?

This works really well for our contact list, containing key words. What I'd like to be able to do, however, is also be able to provide links into this page that is pre-filtered on an optional GET argument.

For example:

  • Default view is: http://somesite/somepage.html
  • Optional entry is: http://somesite/somepage.html?initFilter=abc
    ...where onLoad it would behave as though someone had loaded the default page, and then entered in "abc" to the filter.

Is this possible, and has it been done? If so, it would make this already great script even better, and a perfect match for our needs.

Thanks in advance!
- Dave

first row not filtered

Thanks for the script, very helpful and efficient!! Regarding the first row:

Table index start at 0 not at 1 so to include the first row, just start the loop at 0:
for (var r = 0; r < table.rows.length; r++) instead of
for (var r = 1; r < table.rows.length; r++)

Re: Filter on Multiple Columns?

Once again: This script is GREAT!

I've solved my problem with not being able to filter by two or more specific columns by modifying the two original functions into one super-function in which the user can specify from a drop-down box which column they want to search (a column value of "x" tells the script to search the entire row) and to limit the search to those records that have annotations by clicking on a checkbox. The script is below and i
It works like a charm!

I'm still trying to figure out why the first row of the table does not get filtered out even if it does not match the filter criteria. I'm noticing now that this only happens in FireFox and not in Internet Explorer and since I've modified the script it happens no matter which type of filter I do.


function filter (term, _id){
var searchTerms = term.value.toLowerCase().split(" ");
var table = document.getElementById(_id);
var cellNr = document.form.category.value;
var cellNr2 = 5;
var annotations = document.form.Annotations.value;
var ele;
var notes;
if (cellNr == "x") {
for (var r = 1; r < table.rows.length; r++) {
elerow = table.rows[r].innerHTML.replace(/<[^>]+>/g,"");
notes = table.rows[r].cells[cellNr2].innerHTML;
for (var i = 0; i < searchTerms.length; i++) {
if (annotations == "Annotations") {
if (elerow.toLowerCase().indexOf(searchTerms[i])>=0 && notes == "Annotations") {
table.rows[r].className = 'visiblerow';
}
else {
table.rows[r].className = 'invisiblerow';
}
}
else {
if (elerow.toLowerCase().indexOf(searchTerms[i])>=0) {
table.rows[r].className = 'visiblerow';
}
else {
table.rows[r].className = 'invisiblerow';
break;
}
}
}
}
}
else {
for (var r = 1; r < table.rows.length; r++){
elecell = table.rows[r].cells[cellNr].innerHTML.replace(/<[^>]+>/g,"");
notes = table.rows[r].cells[cellNr2].innerHTML;
if (annotations == "Annotations") {
if (elecell.toLowerCase().indexOf(searchTerms)>=0 && notes == "Annotations") {
table.rows[r].className = 'visiblerow';
}
else {
table.rows[r].className = 'invisiblerow';
}
}
else {
if (elecell.toLowerCase().indexOf(searchTerms)>=0) {
table.rows[r].className = 'visiblerow';
}
else {
table.rows[r].className = 'invisiblerow';
}
}
}
}
}

Filter Results in URL

is it possible to save the filter results in the URL and forward the URL to some else, so that they have the same view as I do.

When I press enter in the form it produces the results in the URL, for eg:- http://www.mysite.com/filt=2008+dec but when paste this URL into a new window I get the whole table instead of the filtered results.

Thanks

PS:- Very nice script!

Thank You!

Worked very well on euco2009istanbul.org/paymentlist.htm . Thank you very much! This is the fastest script I've found for it's job.

Great Work. Great Search.

Great Work. Great Search.

It is very Useful for Us. Great,Great work. It is very simple.

Extra content, keywords without seeing it in table for filtering

Extra content, keywords without seeing it in table for filtering
I want extra keywords, content in my table (links) without seeing it in table for filtering, is that possible?

For example title = AFC Ajax (with extra keywords for filtering, Amsterdamsche, Football, Club, Holland this you don't see etc)

Great Script! Solved a

Great Script!
Solved a problem with Rails and Ajax where i had response times >1sec.
With your script and some minor changes the response time is lightning fast!

Hello, Thanks for your great

Hello,

Thanks for your great work.... Its really simple and superb... Once again thanks a lot..

Jimmy Augustine

Nice

Very good.. Works great!

Thank you.

Excellent script, Managed to

Excellent script,

Managed to integrate it into my site in under 5 minutes with a few modifications.

Cheers!

Search multiple columns

I would like to have multiple text fields, each filtering a column. But I would like their filtering effect to be additive. Anyone know how to do that>

need filter on rowspan column

This script is very good, except that I could not make it work for the rowspan column. Is that possible?

Filter just one column

Is it possible to filter the whole table by searching in just one column?

Take the first version

Yes, this is exactly what the first version on the page does.

changing style of searched words

Is it possible to add a function which would color the word you're searching for on the fly? Say if I'm searching for editor, is it possible to add a function which would color first the e's, then the ed's, edi's, edit's, edito's and editor's? Sort of like the Google toolbar does? Or just the whole word when I pause for a moment? And provided that it is possible, then if the script is changed so as to enable the search for multiple words, like someone here did, is it then possible to change the color for the second word?

My Version

Hi,

nice script.

I made some minor changes to make it fit my needs.

- always search the whole table row (not a single cell, so the third argument is obsolete now)
- allow multiple words separated by whitespace (always boolean AND)

cheers

Stefan

function myfilter (term, _id)
{
var suche = term.value.toLowerCase();

/* mehrere Begriffe durch Leerzeichen getrennt */
var suchwoerter = suche.split(" ");

var table = document.getElementById(_id);
var ele;
var theDisplay;

for (var r = 1; r < table.rows.length; r++){
theDisplay = '';
ele = table.rows[r].innerHTML.replace(/<[^>]+>/g," ").toLowerCase();
for (i = 0; i

something is missing

The nasty comment script does not like < followed by a non whitespace char. So I try again ...

function myfilter (term, _id)
{
var suche = term.value.toLowerCase();

/* mehrere Begriffe durch Leerzeichen getrennt */
var suchwoerter = suche.split(" ");

var table = document.getElementById(_id);
var ele;
var theDisplay;

for (var r = 1; r < table.rows.length; r++){
theDisplay = '';
ele = table.rows[r].innerHTML.replace(/<[^>]+>/g," ").toLowerCase();
for (i = 0; i < suchwoerter.length; i++){

if (ele.indexOf(suchwoerter[i]) == -1 ){
theDisplay = 'none';
}
}
table.rows[r].style.display = theDisplay;
}
}

something is definitely missing

I get a message that a ; is missing in the line
if (ele.indexOf(suchwoerter[i]) == -1 ){
at position 19.
And according to my count, there's either a { missing, or a } to many.

missing code

Hi,

nasty script is doing strip_tags() it seems. You could replace < characted by &lt; and paste the code again. Please...

missing code

Was this ever corrected, I too need to have this script search all the columns in the row and not just the one being passed, but I'm getting the same errors as the previous user.....

Is it possible to modify the

Is it possible to modify the script to allow searching for multiple words?

Script modification

Yes, i've seen it on some websites. It's a slight variation in the code.