Change <tr> color in jQuery Laravel

Viewed 194

Where I have to put IF in jQuery to change color? if I comment the logical IF, data shows normally.

Here is the code

$('.tbody-reply').empty();
        if(data != ""){
            data.forEach(element => {
                $('.tbody-reply').append( ""+
                    "<tr>" +
                        "<td>" + element.description + "</td>" +
                        "<td>" + element.created_at + "</td>" +
                    "</tr>");
                // if(element.idResponder == 'TE')
                //   $('#').css("background-color", "yellow");
            });
        }else{
            $('.tbody-reply').append( ""+
                "<tr>" +
                    "<td align='center' colspan='6'>No Data Found</td>" +
                "</tr>");
        }
4 Answers

You can apply CSS to the rows as you create the new td in your loop function. I have also cleaned up the way you were creating the td elements.

if (response.length) {
  response.forEach(element => {
    let row = $('<tr>'); //create row
    if (element.idResponder == 'TE') { //check if TE
      row.append($('<td>').html(element.description));
      row.append($('<td>').html(element.created_at));
      row.css("background-color", "yellow"); //apply css
    } else {
      row.append($('<td>').html(element.description));
      row.append($('<td>').html(element.created_at));
    }
    table.append(row) //append all data
  });
} else {
  let row = $('<tr>');
  table.append(row)
  row.append($('<td align="center" colspan="6">').html('No Data Found'));
}

Working Demo:

var response = [{
  "description": "Always Helping",
  "created_at": "03-02-2002",
  'idResponder': 'TE'
}, {
  "description": "Foo",
  "created_at": "03-02-2020",
  'idResponder': 'Foo'
}, {
  "description": "Ikra",
  "created_at": "03-02-2020",
  'idResponder': 'TE'
}]

let table = $('.tbody-reply')

if (response.length) {
  response.forEach(element => {
    let row = $('<tr>');
    if (element.idResponder == 'TE') {
      row.append($('<td>').html(element.description));
      row.append($('<td>').html(element.created_at));
      row.css("background-color", "yellow"); //apply css
    } else {
      row.append($('<td>').html(element.description));
      row.append($('<td>').html(element.created_at));
    }
    table.append(row) //append all data
  });
} else {
  let row = $('<tr>');
  table.append(row)
  row.append($('<td align="center" colspan="6">').html('No Data Found'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-hover">
  <thead>
    <tr>
      <th>Name</th>
      <th>Created Date</th>
    </tr>
  </thead>
  <tbody id="tdata" class="tbody-reply">
  </tbody>
</table>

Create a row object first instead of appending the raw html string. Then conditionally modify that object and append the object

const $tr = $(
  "<tr>" +
  "<td>" + element.description + "</td>" +
  "<td>" + element.created_at + "</td>" +
  "</tr>"
)

if (element.idResponder == 'TE') {
  $tr.css("background-color", "yellow")
}

$('.tbody-reply').append($tr);

if I understand you correctly, you want to color the cell when the condition is met. the data variable is an array? if an array, you are incorrectly checking for emptiness. correct variant:

     if(data.length !== 0){
        data.forEach(element => {
            let parent = $('.tbody-reply');
            parent.append( ""+
                "<tr>" +
                    "<td>" + element.description + "</td>" +
                    "<td>" + element.created_at + "</td>" +
                "</tr>");
            if(element.idResponder == 'TE')
                parent.css("background-color", "yellow");
        });
    }else{
        $('.tbody-reply').append( ""+
            "<tr>" +
                "<td align='center' colspan='6'>No Data Found</td>" +
            "</tr>");
    }

One approach is the following:

// dummy data for the example to work with:
const data = [{
  'description': 'something',
  'created_at': Date.now(),
  'idResponder': 'TE'
}, {
  'description': 'other',
  'created_at': Date.now(),
  'idResponder': 'TIE'
}, {
  'description': 'than',
  'created_at': Date.now(),
  'idResponder': 'THE'
}, {
  'description': 'the',
  'created_at': Date.now(),
  'idResponder': 'TEN'
}, {
  'description': 'previous',
  'created_at': Date.now(),
  'idResponder': 'TE'
}, {
  'description': 'entry',
  'created_at': Date.now(),
  'idResponder': 'TEPID'
}];


// caching a reference to the <tbody class="tbody-reply"> element:
const $tbody = $('tbody.tbody-reply');

// emptying out that element:
$('.tbody-reply').empty();

if (data != "") {

  // iterating over the Array of Objects using Array.prototype.forEach():
  data.forEach(
    // with an Arrow function, which passes a reference to the current
    // Object - of the Array of Objects - to the inner body of the
    // function:
    (datum) => {
    
      // here we know the names of the properties we wish to work with, so
      // we can use destructuring to assign those properties to variables
      // within the function block:
      let {
        description,
        created_at,
        idResponder
      } = datum,
      
      // here we use a template literal (delimited with back-ticks) to create
      // the <tr> element, and its children; we use a conditional operator
      // to test if the idResponder variable is equal to 'TE', if it is we
      // return a class-name of 'highlight', and if not we return an empty
      // String:
      tr = `<tr ${ idResponder === 'TE' ? 'class="highlight"' : '' }">
                        <td>${description}</td>
                        <td>${created_at}</td>
                    </tr>`
                
      // we then append the created <tr> to the cached <tbody> element:
      $tbody.append(tr);
    });

} else {
  $tbody.append(`
    <tr>
      <!-- because you didn't post your relevant HTML, or a sample of your
           Array of Objects I couldn't recreate your whole <table> so I only
           created two <td> elements per row; this colspan attribute will
           of course need to be changed back to 6 for your own use -->
      <td align="center" colspan="2">No Data Found</td>
    </tr>`);
}
*,
 ::before,
 ::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

table {
  border-collapse: collapse;
  width: 80vw;
  margin: 1em auto;
  border: 3px solid #aaa;
}

th {
  border-bottom: 2px solid #aaa;
}

tr.highlight {
  background-color: #ffa;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Description:</th>
      <th>Created at:</th>
    </tr>
  </thead>
  <tbody class="tbody-reply">
  </tbody>
</table>

References:

Related