Skip to content

Instantly share code, notes, and snippets.

@MartinBrugnara
Created May 7, 2013 09:14
Show Gist options
  • Save MartinBrugnara/5531342 to your computer and use it in GitHub Desktop.
Save MartinBrugnara/5531342 to your computer and use it in GitHub Desktop.
jQuery Filter - Search Table - with typeahead
var SEARCH_MODE = 1;
$("#search-input").keyup(function(){
if($(this).val() != ""){
// hide all rows
$("#search-table :not(thead, tfoot) tr").hide();
if(SEARCH_MODE==0){
// Mode 0: Require at least one word per row
var search_string = $.map($(this).val().split(/[^a-zA-Z0-9]/), function(e, i){
return "#search-table td:contains-ci('"+e+"')";
}).join(',');
$(search_string).parent("tr").show();
}else /*if(SEARCH_MODE==1) */ {
// Mode 1: Require all words each row
var org = $('#search-table tr');
$.each($(this).val().split(/[^a-zA-Z0-9]/), function(i, e){
if(e.length>0)
org = org.find("td:contains-ci('"+e+"')").parent('tr');
});
org.show();
}
}else{
// If nothing to search --> show all rows
$("#search-table tbody > tr").show();
}
});
$('#search-clean').on('click', function(){
$("#search-input").val('').trigger('keyup');
});
<table id="search-table">
<thead>
<tr>
<th colspan="4">
<input type="text" id="search-input" placeholder="Search">
<a href="#" id="search-clean">Reset</a>
</th>
</tr>
<tr>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
<th>Field 4</th>
</tr>
</thead>
<tbody>
<tr><td>My Data</td><td>My Data</td><td>My Data</td><td>My Data</td></tr>
<tr><td>My Data</td><td>My Data</td><td>My Data</td><td>My Data</td></tr>
<tr><td>My Data</td><td>My Data</td><td>My Data</td><td>My Data</td></tr>
...
</tbody>
<tfoot>
<tr>
<td>Field 1</td>
<td>Field 2</td>
<td>Field 3</td>
<td>Field 4</td>
</tr>
</tfoot>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment