Skip to content Skip to sidebar Skip to footer

How Do I Insert Certain Values Of An Array As A Css Style Property For A In A Dynamic Table?

I have a script that collects data from an array and uses these to generate a dynamic table. Some of these values in the array are Font Awesome styles. My existing script inserts a

Solution 1:

Inside the nested for-loop you can make a distinction based on the current value of keys[b]. If it's paymentStatus add an <i> tag with the css for the font awesome exclamation mark and use the .innerHTML property of the cell. If it's something else just assign the appropriate text to the .innerText proeprty.

var array = [{
  amount: 12,
  payersNumber: 1245,
  paymentStatus: "okay"
}, {
  amount: 24,
  payersNumber: 3345,
  paymentStatus: "okay"
}, {
  amount: 45,
  payersNumber: 4534,
  paymentStatus: "not okay"
}];

table = document.getElementById("table");

var currentTransaction;
var keys = ["payersNumber", "amount", "paymentStatus"];
for (var i = 0; i < array.length; i++) {
  
  var newRow = table.insertRow(table.length);

  currentTransaction = array[i];
  for (var b = 0; b < keys.length; b++) {
    var cell = newRow.insertCell(b);
    if (keys[b] == "paymentStatus") {
      cell.innerHTML = "<i class='fas fa-exclamation-triangle'></i>" + currentTransaction[keys[b]];
    } else {
      cell.innerText = currentTransaction[keys[b]];
    }
  }
}
<linkrel="stylesheet"href="https://use.fontawesome.com/releases/v5.10.0/css/all.css"><linkrel="stylesheet"href="https://use.fontawesome.com/releases/v5.10.0/css/v4-shims.css"><tableid="table"border="1"><tr><th>Number</th><th>Amount</th><th>Status</th></tr></table>

Solution 2:

You can use classList.add method to add css class to HTML element as follows:

for (var b = 0; b < keys.length; b++) {
    var cell = newRow.insertCell(b);
    if (keys[b] == 'paymentStatus') {
        let className = '';
        // it is assumed that paymentStatus value format is consistentconst classNameArr = currentTransaction[keys[b]].split('=');
        if (classNameArr.length === 2) {
            className = classNameArr[1];
            cell.classList.add(className);
        }
    } else {
        cell.innerText = currentTransaction[keys[b]];
    }    
  }

Post a Comment for "How Do I Insert Certain Values Of An Array As A Css Style Property For A In A Dynamic Table?"