DCJones
DCJones

Reputation: 3451

Jquery if statement inside a dynamic table creation

Is it possible to have an "if" statement inside the code below to detect if the data is 1 or 0, if it's "1" change the colour of the table cell background?

My code

$(document).ready(function() {

    var data;
    $.get("get_timeline.php", function(data) {

        response = $.parseJSON(data);
        $.each(response, function(i, item) {
            var $tr = $('<tr>').append(
                $('<td>').text(item.deviceid),
                $('<td>').text(item.mediatype),
                $('<td>').text(item.campainname),
                $('<td>').text(item.medianame),
                $('<td>').text(item.start_date),
                $('<td>').text(item.end_date),
                $('<td>').text(item.uploadflag)).appendTo('#records_table');
        });

    });
});

Many thanks in advance for your time.

Upvotes: 1

Views: 1222

Answers (2)

fdomn-m
fdomn-m

Reputation: 28611

As an alternative to using .toggleClass and instead of using if you can use the conditional operator ?:, to keep your chain, eg:

var $tr = $('<tr>').addClass(data === 1 ? "active" : "").append(

(or, on a single cell directly (note to self, read the question closer...))

$('<td>').addClass(item.active === 1 ? "active" : "").text(item.deviceid)

depends on whether you need a single cell or a the whole row (all cells) - you wouldn't want to add the above to every cell, use css instead eg tr.active>td { background-color: yellow; }

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You can use .toggleClass( className, state) to add a custom class to TD based on condition.

$('<td>').text(item.deviceid).toggleClass('your-class-which-set-background', item.deviceid === 1)

var response = [{
    deviceid: 1
  },
  {
    deviceid: 2
  }
]
$.each(response, function(i, item) {
  var $tr = $('<tr>').append(
    $('<td>').text(item.deviceid).toggleClass('your-class-which-set-background', item.deviceid === 1)
  ).appendTo('#records_table');
});
.your-class-which-set-background {
  background-color: #CCC
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="records_table">
</table>

Upvotes: 0

Related Questions