Skip to content

Instantly share code, notes, and snippets.

@jaymzcd
Created May 17, 2011 15:07
Show Gist options
  • Select an option

  • Save jaymzcd/976648 to your computer and use it in GitHub Desktop.

Select an option

Save jaymzcd/976648 to your computer and use it in GitHub Desktop.
Filter table in HTML via JS on keyup
<script type="text/javascript">
/* Can't remember where I saw this but it's quite handy/cool for tables to do filtering without posts */
$(document).ready(function(){
//add index column with all content.
$(".filterable tr:has(td)").each(function(){
var t = $(this).text().toLowerCase(); //all row text
$("<td class='indexColumn'></td>")
.hide().text(t).appendTo(this);
});//each tr
$("#FilterTextBox").keyup(function(){
var s = $(this).val().toLowerCase().split(" ");
//show all rows.
$(".filterable tr:hidden").show();
$.each(s, function(){
$(".filterable tr:visible .indexColumn:not(:contains('"
+ this + "'))").parent().hide();
});//each
});//key up.
});//document.ready
</script>
<p>Filter data:&nbsp;<input type="text" id="FilterTextBox" name="FilterTextBox" /></p>
<table class="filterable">
<tr>
<th>Name</th>
<th>City</th>
<th>Address</th>
<th>Postcode</th>
</tr>
{% for object in object_list %}
<tr>
<td><a target="_blank" href="#">{{ object.name }}</a></td>
<td>{{ object.city }}</td>
<td>{{ object.address_1 }}<br>{{ object.address_2 }}</td>
<td>{{ object.postcode }}</td>
</tr>
{% endfor %}
</table>
@bzx

bzx commented May 31, 2012

Copy link
Copy Markdown

very nice

@tolotrasam

Copy link
Copy Markdown

Can you make another version of which there are 3 text inputs for each column to filter?

@GirishaVil

Copy link
Copy Markdown

how to limit number of tr display per page ? My modified goes as

  //Helper function that gets a count of all the rows <TBODY> in a table body <TR>
$.fn.rowCount = function() {
    return $('tbody', $(this).find('tr')).length;
};
$("#myTable tr:has(td)").each(function()
{
   var t = $(this).text().toLowerCase(); //all row text one by one
   $("<td class='indexColumn'></td>")//creating a new td with this row data and plays hidden
    .hide().text(t).appendTo(this);
 });//each tr

$("#search").keyup(function(){
   var s = $(this).val().toLowerCase().split(" ");alert(s);
   var rowCount = $('#myTable').rowCount();alert(rowCount);//getting total count of records before search
   //$("#myTable tr:hidden").show();

	//show all rows.
    $.each(s, function(){
       $("#myTable tr:visible .indexColumn:not(:contains('"
          + this + "'))").parent().hide();
       var rowCount1 = $("#myTable tr:visible .indexColumn:not(:contains('"
          + this + "'))").length();alert(rowCount1);
   });//each
   for(var i=0;i<rowCount1;i++) {
   		if(i<rowCount){
   			$("#myTable tr:hidden").show();
   		}
   }
});//key up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment