JQuery: Table Row Show/Hide based on Column Value

自作多情 提交于 2019-12-18 16:46:54

问题


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?


回答1:


DEMO

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



回答2:


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>



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/17722205/jquery-table-row-show-hide-based-on-column-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!