dimanche 18 août 2019

How to use javascript to replace true/false value in html table with a checkbox

I have an array of javascript objects, that I'm using to dynamically populate an html table. I iterate through each object and all is good. However, one of the keys has a value of true/false, and I need to replace the value with a checkbox for each object in the array. How can I do that?

The checkbox needs to be ticked for false and not ticked for true, also the checkboxes need to be disabled, as we don't want a user interaction.

// Draw table from 'products' array of objects 
function drawTable(tbody) {
  var tr, td;
  tbody = document.getElementById(tbody);
  for (var i = 0; i < products.length; i++) // loop through data source
  {
    tr = tbody.insertRow(tbody.rows.length);
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = products[i].ProductName;
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = products[i].UnitsInStock;
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = products[i].UnitPrice;
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = products[i].Discontinued;
    td = tr.insertCell(tr.cells.length);
    td.innerHTML = document.createElement('button');
  }
}

drawTable('table-data')
<h2>Products</h2>

<div class="table-wrapper">
  <table id="display-table" class="fl-table">
    <thead>
      <tr>
        <th>Product Name</th>
        <th>Units In Stock</th>
        <th>Unit Price</th>
        <th>Discontinued</th>
      </tr>
    </thead>
    <tbody id="table-data">

    </tbody>
  </table>
</div>



Aucun commentaire:

Enregistrer un commentaire