bran
bran

Reputation: 167

Using javascript to change table cell background color based on json value

I am trying to display status of clients (up or down) by changing the color table cell background based on json value:

[{
    "client": "client1",
    "ip": "127.0.0.1",
    "status": "up"
}, {
    "client": "client2",
    "ip": "127.0.0.2",
    "status": "up"
}]

My attempt so far:

<script>
$.getJSON("<webaddress>/clients.json",
function (data) {
    var tr;
    for (var i = 0; i < data.length; i++) {
        tr = $('<tr/>');
        tr.append("<td>" + data[i].client + "</td>");
        $('table').append(tr);


        if(data[i].status == "up")
        {
          $('td').css ('background-color', 'green');
         } else {
          $('td').css('background-color', 'red');
         };    

}


});


</script>

<style type="text/css">

.table {
  width: 300px !important;
}

</style>

<div>
<table class="table">
    <tr>
        <th>Clients</th>
    </tr>
</table>
</div>

When status is up the cell background stays green but even if I change one status to down then all cell background turns red. I know its probably something obviously, but it doesnt help that my js knowledge is not that good.

Upvotes: 1

Views: 1733

Answers (2)

Nigrimmist
Nigrimmist

Reputation: 12386

Yeap, by that code

$('td').css ('background-color', 'green');

your all TDs will be green.

To color required td, you need to change it to

$('td',tr).css ('background-color', 'green');

Upvotes: 2

Aman Rawat
Aman Rawat

Reputation: 2625

You are using $('td') which means all the td tag in the document so change that to tr.find('td') there are many other ways to do it. Hope it will work for you

Upvotes: 0

Related Questions