Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to filter table ( table data is populated from JSON file) by using jQuery?

Tags:

json

html

jquery

I have a table which has some user details. I have populated those data from JSON. At the bottom of the table , i have a text field which is provided for users who can type some information to filter the table. For example,

Consider a table contains 10 rows. the first 6 rows contains developer details and the last 4 rows contains tester details. If a user type developer in the text box , then the table should display the rows, which contain information about the developer. how can i achieve this by using jQuery ?

I don't want to post my wrong code here. so please don't ask me to post some code.

like image 1000
arjun Avatar asked Dec 30 '25 16:12

arjun


1 Answers

You can use the filter() jquery function to filter through the rows until you find the ones which <td> matches what you write in a text box and filter after you click a button.

Example:

HTML:

<table id="myTable">
    <thead><tr><td>Member</td><td>Stuff</td></tr></thead>
    <tbody>
        <tr><td>Developer</td><td>1</td></tr>
        <tr><td>Developer</td><td>2</td></tr>
        <tr><td>Developer</td><td>3</td></tr>
        <tr><td>Tester</td><td>4</td></tr>
        <tr><td>Tester</td><td>5</td></tr>
    </tbody>
</table>
<input type="text" id="filter" />
<input type="button" id="btnFilter" value="Filter" />

Javascript:

$(document).ready(function() {
    $("#btnFilter").click(function() {
        $("#myTable tbody tr").show();
        if($("#filter").val.length > 0) {
            $("#myTable tbody tr").filter(function(index, elm) {
                return $(elm).html().toUpperCase().indexOf($("#filter").val().toUpperCase()) < 0;
            }).hide();
        }
    });
});

Working fiddle: http://jsfiddle.net/tKqw9/1/

EDIT: Added toUpperCase() to the text compare part so it compares case insensitive. Also added a compare to the whole <tr> element content so it can search over any cell value in the row.

like image 182
Roberto Linares Avatar answered Jan 01 '26 07:01

Roberto Linares



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!