I’ve started to code a little table rows search snippet in jQuery, and it ended up being a plugin :) So, little snippet explanation, and plugin documentation waiting on you in full article.
Snippet
Functionality is straight forward. You’ll bind this snippet to input type=”text”, and after every keyup event, it’ll take the value of this input, and it’ll hide the table rows, so only the ones with this value/string in them will remain visible.
Here is the snippet with comments:
// Bind the keyup event triggering our
// snippet to text input with class .selector
$("input:text.selector").keyup( function(){
// define variables needed in snippet
var keyWord = $(this).attr("value").toLowerCase(), // our text string we are searching for
tableSelector = "#target", // selector of target table (one/unique table)
tempMesh = ""; // variable for storing temporary tr content to search in
// at least 2 letters long string
if( keyWord.length > 1 ) {
// cycle through all table rows to filter them
$(tableID + " tr").each( function(i,e){
// select the td elements of each tr, as we can't
// manipulate with visibility of tr
var myChildren = $(this).children("td");
// get the text of all td elements
tempMesh = $(this).text().toLowerCase();
// and search in them for our keyword
if( tempMesh.indexOf(keyWord) == -1 ){
// if there is no match, hide tr childrens
myChildren.hide();
}else{
// if there is match, make sure they will be visible
myChildren.show();
}
} );
}else{
// in case of less than 2 letters long keyword,
// return the table into default state
$(tableID + " td").show();
}
});
Table search plugin
Plugin is a little bit more complex with a few options and effects. Usage is simple:
-
$("triggerSelector").tableSearch("tableSelector", {options});
-
Explanation:
- triggerSelector: Could be any object, or array of the objects. According to the object type, it is bonded with the corresponding even type (text input = keyup, radio,checkbox = change, button = click).
In case of inputs, selects, input buttons, or textareas, it is getting their value as a keyword. In case of custom buttons it is getting their text() (what is between tags = <div class=”button”>Keyword</div>) as a keyword. - tableSelector: Navigate plugin to which table you want filter.
- options: There are 3:
- effect: fade, slide, highlight (default = no effect, plain hiding and showing)
- speed: milliseconds (default: 200)
- fadeto: in case of Highlight, this is the opacity into which the not matching rows will fade to [0-1] (default: 0.2)
Example:
-
var tsOptions = {
'effect' : 'highlight',
'speed' : 100,
'fadeto' : 0.1
}
$("input:text.selector").tableSearch("#myTable", tsOptions);
-
Now just start typing in this input and it will filter the table as you are touching the keyboard :) Here is the demo and plugin download.
No comments yet Leave a comment
Empty space needs to fill up! :)
Leave a comment TrackBack URL RSS feed for comments on this post.