user3265065
user3265065

Reputation:

How can I change td background color depending on value in a table using JavaScript / jQuery?

I am inserting append data dynamically into a product table. There are some td column. Now I want to change background color depending on available product using JavaScript/jQuery.

Appending data into table like this:

function getProductData(name, code, rate, available) {
    $('#test tr:last').after("<tr><td><input value='" + name + "'></td><td><input value='" + Code + "'></td><td><input value='" + rate + "'></td><td><input id='available_" + id + "' value='" + available + "' ></td></tr>");
}

Here is my table:

<tbody id="test">
    <tr>
        <td></td>
    </tr>
</tbody>

Table is showing all data perfectly. Now I need to change background color for for the available column depending on their values : like :: if available > 0 then green color < 0 then red color.

Please me out. Help is highly appreciated.

Upvotes: 0

Views: 2159

Answers (1)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try,

$('#test [id^="available_"]').each(function(){

   var closestTd = $(this).closest('td');
   var valueCache = parseInt($(this).val());

   if(valueCache > 0) {
      closestTd .addClass('positive');
   }
   else if(valueCache < 0) {
      closestTd.addClass('negative');
   }
   else {
      //Apply any color as per your wish for value = 0;
   }

});

And define css rules for that classes,

.positive{  background-color : green; } 
.negative{  background-color : red; }

Upvotes: 2

Related Questions