Dkage Dkage - 2 months ago 13
Javascript Question

Change cell color in a table

My page has a table with 3 columns, which are:


  1. Member name

  2. Obligatory to fill the form

  3. Status



Column 2 has the values "Yes" or "No" and column 3 can have "Pending", "Started" or "Finished" values.

I want to make the color of the text in the column 3 change depending on the status, so I did the following js.

$("td[headers ='STATUS']").each(function () {
if($(this).text() == 'Pending'){
$(this).css("color", "red");
}
else if($(this).text() == 'Finished'){
$(this).css("color", "green");
}
else if($(this).text() == 'Started'){
$(this).css("color", "#B8B800");
};
});


It is working as intended. But now I want to only change the colors of the column 3, when column 2 has a value "Yes" for obligatory, else it is supposed to stay black.

Is there a way to mix my "if" to check the other column?

Answer

I would change my concept, to run on rows, not on all cells, and do my checks "per line".

This is what it will look like:

JS:

    $(function () {
    $("tbody tr").each(function () {
        var cols = $(this).children("td");
        if ($(cols[1]).text() == "Yes") {
            var statusEle = $(cols[2]);
            switch (statusEle.text()) {
                case 'Pending':
                    statusEle.css("color", "red");
                    break;
                case 'Finished':
                    statusEle.css("color", "green");
                    break;
                case 'Started':
                    statusEle.css("color", "#B8B800");
                    break;
            }
        }
    });
});

HTML:

<table>
<thead>
    <tr>
        <th>Name</th>
        <th>Is Obligated</th>
        <th>Status</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>John</td>
        <td>Yes</td>
        <td>Single</td>
    </tr>
    <tr>
        <td>Doe</td>
        <td>No</td>
        <td>Pending</td>
    </tr>
    <tr>
        <td>CRAP</td>
        <td>Yes</td>
        <td>Pending</td>
    </tr>
    <tr>
        <td>John</td>
        <td>Yes</td>
        <td>Finished</td>
    </tr>
</tbody>

Working fiddle