简体   繁体   中英

JQuery: Table Row Show/Hide based on Column Value

I have a table that has a column with Yes/No as possible values

<table id="mytable">
<thead>
<tr>
    <th>
        Col1
    </th>
    <th>
        Col2
    </th>

    <th>
        ActiveYN
    </th>
</tr>
</thead>
<tbody>
<tr>
    <td>
        Apple
    </td>
    <td>
        12345
    </td>

    <td>
        Yes
    </td>
</tr>
<tr>
    <td>
        Orange
    </td>
    <td>
        67890
    </td>

    <td>
        No
    </td>
</tr>
<tr>
    <td>
        Mango
    </td>
    <td>
        456745
    </td>

    <td>
        Yes
    </td>
</tr>

I need to show the row if ActiveYN is 'Yes' and Hide id ActiveYN is 'No' How can i access the ActiveYN inside JQuery and show/hide accordingly?

DEMO

$('button').on('click', function () {
    var $rowsNo = $('#mytable tbody tr').filter(function () {
        return $.trim($(this).find('td').eq(2).text()) === "No"
    }).toggle();
});

How about something like this: $('td:contains("No")').parent().hide();

Live Demo

JS

$('input').click(function(){
    $('td:contains("No")').parent().toggle();
}); 

HTML

<input type='button' value='hide/show' />

<table id="mytable">
<thead>
<tr>
    <th>
        Col1
    </th>
    <th>
        Col2
    </th>

    <th>
        ActiveYN
    </th>
</tr>
</thead>
<tbody>
<tr>
    <td>
        Apple
    </td>
    <td>
        12345
    </td>

    <td>
        Yes
    </td>
</tr>
<tr>
    <td>
        Orange
    </td>
    <td>
        67890
    </td>

    <td>
        No
    </td>
</tr>
<tr>
    <td>
        Mango
    </td>
    <td>
        456745
    </td>

    <td>
        No
    </td>
</tr>

usually I would add this as an attribute on the row:

<tr data-active="No">
....
</tr>

Then to hide them all you can do:

$(function(){

$("[data-active=No]").hide();
});

Or you can add different classes/styles based on the value when it creates the table.

You can do it from server side itself.

@if (item.ActiveYN) {
    <tr style="display: none;">
} else {
    <tr>
}

I don't know the razor syntax, but you get the idea.

To be able to do it from client-side, add a class.

@if (item.ActiveYN) {
    <tr class="hideMe">
} else {
    <tr>
}

And then in jQuery:

$('.hideMe').hide();

Edited again after your question was edited, now if we forget the server-side altogether:

$("mytable").find("tr:contains('No')").hide();

Use this statement in your button click handler function. But, remember it will also find any text which contains "No" anywhere in a row. To make it more precise, use regular expressions to search exactly a "No".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM