jquery - Searching HTML Table -
i have created table html , want integrate search box. how do that? can recommend jquery plugin or better complete tutorial?
a quick , dirty approach, using jquery:
$(document).ready( function(){ $('#searchbox').keyup( function(){ var searchtext = $(this).val(); if (searchtext.length > 0){ $('td:contains(' + searchtext +')') .css('background-color','#f00'); $('td:not(:contains('+searchtext+'))') .css('background-color','#fff'); } }); });
with following (x)html:
<table> <thead> <tr> <td colspan="2"> <label for="searchbox">search:</label> <input type="text" id="searchbox" /> </td> </tr> </thead> <tbody> <tr> <td>something</td> <td>more text</td> </tr> <tr> <td>lorem ipsum</td> <td>blah?</td> </tr> </tbody> </table>
edited use addclass()
/removeclass()
, in place of setting css in jquery itself:
$(document).ready( function(){ $('#searchbox').keyup( function(){ var searchtext = $(this).val(); if (searchtext.length > 0){ $('td:contains(' + searchtext +')') .addclass('searchresult'); $('td:not(:contains('+searchtext+'))') .removeclass('searchresult'); } else if (searchtext.length == 0) { $('td.searchresult') .removeclass('searchresult'); } }); });
to fade out table cells don't contain search result can use following:
jquery:
$(document).ready( function(){ $('#searchbox').keyup( function(){ var searchtext = $(this).val(); if (searchtext.length > 0) { $('tbody td:contains('+searchtext+')') .addclass('searchresult'); $('.searchresult') .not(':contains('+searchtext+')') .removeclass('searchresult'); $('tbody td') .not(':contains('+searchtext+')') .addclass('faded'); $('.faded:contains('+searchtext+')') .removeclass('faded'); } else if (searchtext.length == 0) { $('.searchresult').removeclass('searchresult'); $('.faded').removeclass('faded'); } }); });
css:
td.faded { opacity: 0.2; }
Comments
Post a Comment