0

Can you please help me code Jquery right way so i can filter HTML table based on text input. So far this is my code:

    <input type="text" name="inputdata" id="inputdata" onkeyup="filter()">
    <table>
            <tr>
                <th>ID</th>
                <th>Name</th>
            </tr>
            <tr name="data">
               <?php foreach ($products as $row) { ?>
                 <td><?php echo $row->id_product; ?></td>
                 <td><?php echo $row->name; ?></td>
               <?php }  ?>
            </tr>

Jquery code

<script>
    function filter(){
        inp = $('#inputdata').val()
        $("tr").filter(function() {
            return $(this).text().indexOf(inp) == -1;
        }).hide();
    }
</script>

So my problems are:

  1. Search is case sensitive
  2. When i input some string, let's say Pants, Jquery filters data, but then i have to refresh a page, so i can search again. Or let me put this other way... When i delete inputted data in search field, table isn't refreshed. It just stay on Pants data, so for another search i have to reload web page
  3. <th> are removed when searching for data. If i declare $('tr[name=data]').filter(function() { search stop working

thx in advance for helping me!

3
  • 1
    What did you try and what is wrong? Commented Feb 24, 2014 at 21:04
  • I have writed down my 3 problems under the code... Commented Feb 24, 2014 at 21:09
  • Those aren't problems, they are requests. Commented Feb 24, 2014 at 21:10

1 Answer 1

3

This should take care of your issues:

<script>
function filter(){
    inp = $('#inputdata').val()
    // This should ignore first row with th inside
    $("tr:not(:has(>th))").each(function() {
        if (~$(this).text().toLowerCase().indexOf( inp.toLowerCase() ) ) {
            // Show the row (in case it was previously hidden)
            $(this).show();
        } else {
            $(this).hide();
        }
    });
}
</script>
Sign up to request clarification or add additional context in comments.

8 Comments

Dude you totaly fixed first two problems! thank you kind sir! Thank you
I've added also a fix for the 3th issue (rows with th are now ignored)
Yep, this totaly did it! Really thank you for that. Look like i got still much to learn, how to handle Jquery code.
Yw.. btw you have the same last name as my uncle :D
No way! :) Where is your uncle from? Probably you are Italian and your uncle is from Slovenia or Croatia... Did i guess right? :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.