Home > Software engineering >  Dynamic employee table and how to css style
Dynamic employee table and how to css style

Time:04-15

I wanted to dynamically create an employee table from a dataset. And I wanted to figure out how to bold all the department names, or supervisors.

Here is a sample of my code:

var data = [{"name": "John Smith", "primary": 1, "title": "CEO", "phone":123}, {"name":"Frank Beans", "title": "COO", "phone": 333}, {"name": "test", "title": " newemployee", "phone": 555}, {"name": "Damar", "primary": 1, "title": "supervisor of quality", "phone": 999}]

function buildTable(data){
    var table = document.getElementById('mytable')

    for(var i =0; i < data.length; i  ){
        var row = `
        <tr>
            <td data-id="primary">${data[i].name}</td>
            <td>${data[i].title}</td>
            <td>${data[i].phone}</td>
        </tr>`
        table.innerHTML  = row
    }
}

I am able to display the table, which is great! But, when I try to bold the td cell that has name it bolds all the name cells. I would like to bold John Smith and Damar since John is the CEO and Damar is a supervisor. I was thinking of looping through the data and if it has primary === 1 then I could apply the bold to the cell but couldn't figure out how to do that.

CodePudding user response:

You could create class

.bold-td {
        font-weight: 700;
 }

then check in a loop if current entry has primary set to 1, if so add class to current td element

for(var i = 0; i < data.length; i  ){
    var row = `
    <tr>
        <td data-id="primary"`;

    if(data[i].primary === 1)
        row = ` `;

    row  = `>${data[i].name}</td>
        <td>${data[i].title}</td>
        <td>${data[i].phone}</td>
    </tr>`;
    table.innerHTML  = row;
}
  • Related