valuevalue

Dynamically change the CSS class of a row in a table.

I have a simple table:

<table> <tr class="none"><td>value</td><td>value</td></tr></table>

Then I need to check all the cell values ​​in each row. If for a given string all the values ​​do not match, then I need to change the string class from "none" to "active". Is there a way to do this using jQuery?

+3
source share
4 answers

Something like below will work. In addition, I recommend using <thead>and <tbody>in <table>for proper markup. Update the corrected function below to check the values ​​of other lines; as soon as another value is met, it is <tr>updated by the corresponding class.

: http://jsfiddle.net/kaCAF/4/

<script type="text/javascript">
$(document).ready(function() {
    $('#myTable tbody tr').each(function() {

        //compare each cell to adjacent cells
        $(this).find('td').each(function() {
            var $val = $(this).text();

            //checks for different values.  as soon as a difference
            //is encountered we move to next row
            $(this).parent().find('td').each(function() {
                if ($(this).text() != $val) {
                    $(this).parent().addClass('different');
                    return false;
                }
            });
        });
    });

});
</script>

<table id="myTable" border="1">
    <thead>
        <tr><th>Col1</th><th>Col2</th><th>Col3</th></tr>
    </thead>
    <tbody>
        <tr><td>Val 1</td><td>Val 1</td><td>Val 2</td></tr>
        <tr><td>Val 1</td><td>Val 2</td><td>Val 2</td></tr>
        <tr><td>Val 3</td><td>Val 3</td><td>Val 3</td></tr>
        <tr><td>Val 123</td><td>Val 123</td><td>Val 123</td></tr>
    </tbody>
</table>
+6

, , , :

$(document).ready(function() {
    var baseval = "";
    $("table tr.active td").each(function() {
        if (baseval == "") {
            baseval = $(this).text();
        }
        else {
            if ($(this).text() != baseval) {
                $(this).parents("tr").removeClass("active");
                $(this).parents("tr").addClass("none");
            }
        }

    });

});

: http://jsfiddle.net/thomas4g/VVTjb/3/

+2

You can get the first td and compare with another:
See http://jsfiddle.net/bouillard/maCBh/

0
source
$(document).ready(function () {
    $('table tr').each(function(){
       var cells = $(this).find('td');
       if(!compareCells(cells)){
          $(this).addClass('active');
       }
    });    
});

 function compareCells(cells){
    var i = cells.length;
    for (i=0;i<cells.length-1;i++)
    {
        if($(cells[i]).html() != $(cells[i+1]).html()){
            return false;
        }
    }
    return true;

}
0
source

All Articles