jquery search filter

While working on tables with huge data and pagination, you might want to make the contents searchable and jquery allows you to do that easily.

First of all, add a search field in your page and give it an id. For this example, we're giving it the id search.

<input type="text" name="" id="search">

Now, we'll add a jquery script that'll be triggered by keyup function on that id. You can add a button too and trigger the event on submit as well.

				
<script>
$("#search").keyup(function() {
	var value = $(this).val().toLowerCase();

	$("table tr").filter(function() {
		$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
	});
});
</script>	

Once the jquery is triggered it'll convert the value sent via that field into lowercase and store in a variable named value here.

$("table tr").filter(function() {}) function will run through each table row content and check if any text in that row matches the value retrieved from the search field.

Finally, $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) will hide all the table rows that don't contain the specified value in one of their <td> and display only those <tr> that contain at least one <td> that matches the value sent via search field.

All the other table rows will return a value of -1 except those with content that matches the value sent via search field.

Alternatively, you can also write it the easier way as shown below and the result would be same.

<script>
$("#search").keyup(function() {
	var value = $(this).val().toLowerCase();
	if(value.length > 0){
		$("table tr").filter(function() {
			var data = $(this).text().toLowerCase().indexOf(value);
			if(data < 1){
				$(this).hide();
			}else{
				$(this).show();
			}
		});
	}
});
</script>	

This way, you can add search functionality in your webpages with data in tabular format with greater convenience. You can even use this jquery search filter to find contents in a <div>, <p> or even <li> elements by simply replacing the HTML elements table tr from the script.


0 Like 0 Dislike 0 Comment Share

Leave a comment