Doug Peters
Doug Peters

Reputation: 529

Change dynamically generated table row background color

I need to be able to dynamically change the table-row bg color like this:

Green, if acc.Amount < acc.Balance

Red, if acc.Amount > acc.Balance

No change, if acc.Amount == acc.Balance

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax
        ({
            type: "GET",
            url: "/Account/Get/@ViewBag.AccountId",
            dataType: 'json',
            success: function(data) {
                $.each(data, function (i, acc)
                {
                    $('<tr>').append(
                        $('<td>').text(acc.Amount),
                        $('<td>').text(acc.Balance))
                        .appendTo('#myTable');
                });
            },
            error: function() {
                alert('Failed');
            }
        });
    });
</script>

How do I inject the table row bg color?

Upvotes: 1

Views: 2398

Answers (1)

Jack
Jack

Reputation: 9388

I've updated your script to include logic to determine amount/balance equality and then applying either an inline style or a class (recommended) to your table row.

The class approach would require you to update your CSS.

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax
        ({
            type: "GET",
            url: "/Account/Get/@ViewBag.AccountId",
            dataType: 'json',
            success: function(data) {
                $.each(data, function (i, acc)
                {
                    var amount = parseInt(acc.Amount, 10),   // parse in case string
                        balance = parseInt(acc.Balance, 10), // parse in case string
                        color = amount < balance ? 'green' : 
                                amount > balance ? 'red' :
                                '';

                    $('<tr>').append(
                        $('<td>').text(acc.Amount),
                        $('<td>').text(acc.Balance))

                        // I'm applying both an inline style and a class name
                        .css('background-color', color) // inline-style
                        .addClass(color) // adding class red/green

                        // continue code...
                        .appendTo('#myTable');
                });
            },
            error: function() {
                alert('Failed');
            }
        });
    });
</script>

Upvotes: 3

Related Questions