Change Row Color based on td value using Jquery

2020-03-19 03:26发布

I have a table that gets populated from a database. I have 2 conditions that i need to apply

  1. Apply Zebra striping to the Table (Completed)
  2. Change Row color to red based td value

​`

<tr class="alt">
    <td class="status"><input type="text" value="One"></td>
    <td class>Received</td>
</tr>
<tr class="alt">
    <td class="status"><input type="text" value="One"></td>
    <td class>Received</td>
</tr>
<tr class="alt">
    <td class="status"><input type="text" value="Zero"></td>
    <td class>Received</td>
</tr>
<tr class="alt">
    <td class="status"><input type="text" value="One"></td>
    <td class>Received</td>
</tr>
<tr class="alt">
    <td class="status"><input type="text" value="Zero"></td>
    <td class>Received</td>
</tr>

​`

$(document).ready(function()
{
$("tr.alt:even").css("background-color", "#f0f8ff");
$("tr.alt:odd").css("background-color", "#fcfceb");
});

$(document).ready(function() {
   $('.status.val():contains("Zero")').closest('tr.alt').css('background-color', '#cd0000');
});

I wanna change the row color based on the input value

<td class="status"><input type="text" value="One"></td>

Here is a fiddle of what I've done so far

Would appreciate the help.

2条回答
我欲成王,谁敢阻挡
2楼-- · 2020-03-19 04:09

To change the tr (you're using v 1.6.4 instead of latest so we need bind instead of on)

$(document).ready(function(){

    $("tr.alt:even").addClass("even");
    $("tr.alt:odd").addClass("odd");
    $('td.status input').bind('change keyup', function(){
        var tr=$(this).closest('tr');

        if ($(this).val()=='Zero') tr.addClass('zero');       
        else tr.removeClass('zero');

    }).trigger('change'); // the trigger is to run this action on load
});
​
tr.odd
{
    background-color:#fcfceb;
}

tr.even
{
    background-color:#f0f8ff;
}

tr.odd.zero
{
    background-color:#ff0000;
}
tr.even.zero
{
    background-color:#cc0000;
}

Your HTML is a bit messed up though. You have missing quotes and <td class> is invalid.

http://jsfiddle.net/MMEhc/158/

EDIT: Updated version to suit the values being changed manually, not just those that are outputted (as I understood the question to be)

http://jsfiddle.net/MMEhc/159/

You'll see I moved the background colours out of the HTML and into the CSS to make it easier to manipulate. I also adjusted the red for even or odd rows.

查看更多
▲ chillily
3楼-- · 2020-03-19 04:16

Try this,

Live Demo

$('td.status[value=Zero]').css('background-color', 'red');

Edit: Based on comments and change in OP

To change the whole row with the given criteria of td you can do it this way.

Live Demo

$('td.status[value=Zero]').closest('tr').css('background-color', 'red');
查看更多
登录 后发表回答