Friday, 21 August 2020

jQuery - HTML Table to DataTables

Currently I have code that query's lists from three separate subsites and then populates that data that I am calling for into an html table.

I want to spice up the table just a bit, I was thinking something along the lines of a DataTable but that is too much work. What would be the easiest way to make this HTML table have a search tool/filter tool?

function loadData(source, url) {
  return fetch(url, {
      headers: {
        accept: "application/json; odata=verbose"
      }
    }) // make request
    .then((r) => {
      if (!r.ok) throw new Error("Failed: " + url); // Check for errors
      return r.json(); // parse JSON
    })
    .then((data) => data.d.results) // unwrap to get results array
    .then((results) => {
      results.forEach((r) => (r.source = source)); // add source to each item
      return results;
    });
}

window.addEventListener("load", function() {
  Promise.all([
      loadData("xDeliverables", "/_api/web/lists/getbytitle('xDeliverables')/items?$select=Program,To,Date,Approved,Notes"),
      loadData("yDeliverables", "/_api/web/lists/getbytitle('yDeliverables')/items?$select=Program,To,Date,Approved,Notes"),
      loadData("zDeliverables", "/_api/web/lists/getbytitle('zDeliverables')/items?$select=Program,To,Date,Approved,Notes"),
    ])
    .then(([r1, r2, r3]) => {
      const objItems = r1.concat(r2, r3);
      var tableContent =
        '<table id="deliverablesTable" style="width:100%" border="1 px"><thead><tr><td><strong>Program</strong></td>' +
        "<td><strong>To</strong></td>" +
        "<td><strong>Date Submitted</strong></td>" +
        "<td><strong>Approved</strong></td>" +
        "<td><strong>Notes</strong></td>" +
        "<td><strong>Source</strong></td>" +
        "</tr></thead><tbody>";

      for (var i = 0; i < objItems.length; i++) {
        tableContent += "<tr>";
        tableContent += "<td>" + objItems[i].Program + "</td>";
        tableContent += "<td>" + objItems[i].To + "</td>";
        tableContent += "<td>" + objItems[i].Date + "</td>";
        tableContent += "<td>" + objItems[i].Approved + "</td>";
        tableContent += "<td>" + objItems[i].Notes + "</td>";
        tableContent += "<td>" + objItems[i].source + "</td>";
        tableContent += "</tr>";
      }
      $("#deliverables").append(tableContent);
    })
    .catch((err) => {
      alert("Error: " + err);
      console.error(err);
    });
});
td {
  text-align: center;
  vertical-align: middle;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="EmployeePanel">
  <table id='deliverablesTable' style="width: 100%;" border="1 px">
    <tr>
      <td>
        <div id="deliverables" style="width: 100%"></div>
      </td>
    </tr>
  </table>
</div>


from jQuery - HTML Table to DataTables

No comments:

Post a Comment