I am creating dynamic HTML content via JS to display table of users
I am getting the data array from the local storage and loop on it and create markup variable and insert it to the HTML
I need to make if condition if the user age bigger than 50 so make the background of the row red
This is my code
function displayUsers() {
let markUp = ``;
for (let i = 0; i < usersContainer.length; i++) {
markUp += `<tr><td>${usersContainer[i].no}</td><td>${usersContainer[i].name}</td><td>${usersContainer[i].email}</td><td>${usersContainer[i].tel}</td><td>${usersContainer[i].dob}</td><td>${usersContainer[i].rmk}</td><td><button class="btn btn-danger" onclick="deleteUser(${i})"><i class="fas fa-trash-alt"></i></button></td></tr>`;
}
$('#tableBody').html(markUp);
}
>Solution :
I would recommend calculating the age based on dob, and then setting the color based on the condition, like this:
function displayUsers() {
let markUp = '';
for (let i = 0; i < usersContainer.length; i++) {
// Format the DB to get the age.
const dob = usersContainer[i].dob;
const age = (your age calculation code here based on dob);
markUp += `<tr style="background:${age > 50 ? '#FF0000' : '#FFFFFF' }">`;
markUp += `<td>${usersContainer[i].no}</td>`;
markUp += `<td>${usersContainer[i].name}</td>`;
markUp += `<td>${usersContainer[i].email}</td>`;
markUp += `<td>${usersContainer[i].tel}</td>`;
markUp += `<td>${usersContainer[i].dob}</td>`;
markUp += `<td>${usersContainer[i].rmk}</td>`;
markUp += `<td>`;
markUp += `<button class="btn btn-danger" onclick="deleteUser(${i})">`;
markUp += `<i class="fas fa-trash-alt"></i>`;
markUp += `</button>`;
markUp += `</td>`;
markUp += `</tr>`;
}
$('#tableBody').html(markUp);
}