Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript make if condition while creating HTML mark up in JS

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading