Removing only the closest thead on table filtering

189 Views Asked by At

I am attempting to remove only the closest thead when filtering with this line of JS "$("tr:not(.wb-hide)").closest("thead").addClass("wb-hide");". The issue is both thead's are getting removed. Any thoughts or solutions would be greatly appreciated.

https://jsfiddle.net/fdjd1obb/

HTML

<label for="idfilter">Find an item:</label>&nbsp;
<input type="text" id="idfilter">
<table>
    <thead>
        <tr>
            <th>Quantity shipped</th>
            <th>Description</th>
            <th>Identifier</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>questionnaire</td>
            <td>1234</td>
        </tr>
        <tr>
            <td>1</td>
            <td>questionnaire</td>
            <td>1235</td>
        </tr>
        <tr>
            <td>1</td>
            <td>questionnaire</td>
            <td>1236</td>
        </tr>
    </tbody>
</table>
<table>
    <thead>
        <tr>
            <th>Quantity shipped</th>
            <th>Description</th>
            <th>Identifier</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>questionnaire</td>
            <td>1237</td>
        </tr>
        <tr>
            <td>1</td>
            <td>questionnaire</td>
            <td>1238</td>
        </tr>
        <tr>
            <td>1</td>
            <td>questionnaire</td>
            <td>1239</td>
        </tr>
    </tbody>
</table>

CSS

.wb-hide {
    display:none;
}

JS

    $(document).ready(function () {
        $('#idfilter').focus().keyup(function () {

            var idFilter = $("#idfilter");

            $("tbody tr td:nth-child(3):not(:contains('" + idFilter.val() + "'))").parent("tr").addClass("wb-hide");
            $("tbody tr td:nth-child(3):contains('" + idFilter.val() + "')").parent("tr").removeClass("wb-hide");

            if (idFilter.val() == 0) {
                $("tr").removeClass("wb-hide");
            }

            $("tr:not(.wb-hide)").closest("thead").addClass("wb-hide");

        });
    });
1

There are 1 best solutions below

0
On

Try this fiddle:

$('thead').addClass("wb-hide");
$("tbody>tr:not(.wb-hide)").parents('table').find('thead').removeClass("wb-hide");

in place of

$("tr:not(.wb-hide)").closest("thead").addClass("wb-hide");