leora
leora

Reputation: 196679

How can I have text in a textbox be used to filter rows in an html table using jquery?

I have an html table like this:

<table>
       <tr><th>Column Heading</th></tr>
       <tr><td>ABC</td></tr>
       <tr><td>DEF</td></tr>
       <tr><td>ABC</td></tr>
       <tr><td>223</td></tr>
       <tr><td>ABCDEF</td></tr>
</table>

and I have an html textbox and I want the functionality when I type text into the textbox, it uses that to filter the html table rows based on content in that first column

So if I type in "AB" into the textbox one 3 rows would still show and the other ones would be hidden. If I remove the "AB" then all rows show again.

What is the most efficent way to hide rows in an html table based on filtering based on content entered into a textbox?

Upvotes: 1

Views: 2510

Answers (3)

Sadikhasan
Sadikhasan

Reputation: 18600

HTML

<input type="textbox" id="text"/>
<table id="table">
       <tr><th>Column Heading</th></tr>
       <tr><td>ABC</td></tr>
       <tr><td>DEF</td></tr>
       <tr><td>ABC</td></tr>
       <tr><td>223</td></tr>
       <tr><td>ABCDEF</td></tr>
</table>

jQuery

$('#text').keyup(function() {
    var text = $(this).val();
    $('#table tr').each(function() {
        var val = $(this).text();
            if( val.toLowerCase().indexOf(text)>=0) {
            $(this).show();
        }
        else {
            $(this).hide();
        }
    });
});

Demo

Upvotes: -1

Umesh Sehta
Umesh Sehta

Reputation: 10681

try this in html:-

<input type="text" class="search"/>

<table>
<thead>
   <tr><th>Column Heading</th></tr>
    </thead>
<tbody>
   <tr><td>ABC</td></tr>
   <tr><td>DEF</td></tr>
   <tr><td>ABC</td></tr>
   <tr><td>223</td></tr>
   <tr><td>ABCDEF</td></tr>
 </tbody>
</table>

and Jquery:-

$('.search').keyup(function(){
    var val=$(this).val().toLowerCase();    
    $('table tbody tr').hide();
     var trs=$('table tbody tr').filter(function(d){
       return $(this).text().toLowerCase().indexOf(val)!=-1;
     });
     trs.show();   
 });

Demo

Upvotes: 4

Michael Dowd
Michael Dowd

Reputation: 231

I think this should get you going in the right direction

$('#myTextbox').keyup(function() {
	var text = $(this).val();
	
	$('#myTable tr').each(function() {
		if($(this).find('td').first().html() == text) {
			$(this).show();
		}
		else {
			$(this).hide();
		}
	});
});

Upvotes: 0

Related Questions