JQuery: Table Row Show/Hide based on Column Value

2020-02-28 12:30发布

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?

4条回答
劫难
2楼-- · 2020-02-28 13:06

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".

查看更多
Emotional °昔
3楼-- · 2020-02-28 13:15

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.

查看更多
倾城 Initia
4楼-- · 2020-02-28 13:19

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>
查看更多
我想做一个坏孩纸
5楼-- · 2020-02-28 13:27

DEMO

$('button').on('click', function () {
    var $rowsNo = $('#mytable tbody tr').filter(function () {
        return $.trim($(this).find('td').eq(2).text()) === "No"
    }).toggle();
});
查看更多
登录 后发表回答