griboedov
griboedov

Reputation: 886

Show rows in table with cells name attribute containing string from input (JQuery)

I would like to have keyup function that would show only rows matching the input text by cell that spans on multiple rows. Consider following table:

  <table border='1'>
    <tr>
        <td rowspan='2'>Key1</td>
        <td name='Key1'> dummy1 </td>
    </tr>
     <tr>
        <td name='Key1'> dummy2 </td>
     </tr>
     <tr>
        <td rowspan='2'>Key2</td>
        <td name='Key2'> dummy3 </td>
    </tr>
     <tr>
        <td name='Key2'> dummy4 </td>
     </tr>
</table>

jsfiddle

Here each row has second td tag with name that matches its "parent" column text. So when I type 'Key1' at the input field I would like it to show only dummy1 and dummy2. Is it possible in jquery?

Upvotes: 1

Views: 764

Answers (3)

renakre
renakre

Reputation: 8291

I understand that you want to display the rows that has a matching name. If this is wrong, please elaborate more, then I can update it.

Here is a demo: https://jsfiddle.net/erkaner/gugy7r1o/33/

$('input').keyup(function(){
   $('tr').hide();
   $("td").filter(function() {
      return $(this).text().toLowerCase().indexOf(keyword) != -1; }).parent().show().next().show();
   });
});

Upvotes: 2

Tomuke
Tomuke

Reputation: 879

Firstly, I would recommend using <ul> to wrap each key in as tables should be used for data structure (Forgive me if that is what it is being used for).

Secondly, just attach an on keyup event to the search box and then find matches based on the id. See example below:

JS Fiddle Demo

It is also worth mentioning that it could be useful attaching a timeout to the keyup event if you end up having large amounts of rows so that only one filter is fired for fast typers!

Upvotes: 1

Jack
Jack

Reputation: 8941

Here's my take on your issue, assuming you always want the first column to show. https://jsfiddle.net/gugy7r1o/2/

<input type="text" id="myInput" />

<table border='1'>
    <tr>
        <td rowspan='2'>Key1</td>
        <td name='Key1' class="data"> dummy1 </td>
    </tr>
     <tr>
        <td name='Key1' class="data"> dummy2 </td>
     </tr>
     <tr>
        <td rowspan='2'>Key2</td>
        <td name='Key2' class="data"> dummy3 </td>
    </tr>
     <tr>
        <td name='Key2' class="data"> dummy4 </td>
     </tr>
</table>

.data{
    display:none;
}

var theData = $('td.data');

var input = $('#myInput').on('keyup', function(){
    theData.hide();
    var value = input.val();

    var matches = theData.filter('[name="'+value+'"]');
    matches.show();
});

Upvotes: 1

Related Questions