Dynamically created html table data not showing in order as expected

Codiq

function CreateWeakHeader(name) {

  var tr = document.createElement('tr');
  var td = document.createElement('td');
  td.classList.add("cal-usersheader");
  td.style.color = "#000";
  td.style.backgroundColor = "#7FFF00";
  td.style.padding = "0px";
  td.appendChild(document.createTextNode(name));

  tr.appendChild(td);


  var thh = document.createElement('td');
  thh.colSpan = "31";
  thh.style.color = "#FFFFFF";
  thh.style.backgroundColor = "#7FFF00";
  tr.appendChild(thh);

  return tr;

}

function htmlTable(data, columns) {
  var header = document.createElement("div");
  header.classList.add("table-responsive");

  var header2 = document.createElement("div");
  header2.id = "calplaceholder";

  header.appendChild(header2);

  var header3 = document.createElement("div");
  header3.classList.add("cal-sectionDiv");

  header2.appendChild(header3);




  if ((!columns) || columns.length == 0) {
    columns = Object.keys(data[0]);
  }



  var tbe = document.createElement('table');
  tbe.classList.add("table", "table-striped", "table-bordered");
  var thead = document.createElement('thead');
  thead.classList.add("cal-thead");
  tbe.appendChild(thead);

  var tre = document.createElement('tr');
  for (var i = 0; i < columns.length; i++) {
    var the = document.createElement('th');
    the.classList.add("cal-toprow");
    the.textContent = columns[i];
    tre.appendChild(the);
  }

  thead.appendChild(tre);

  var tbody = document.createElement('tbody');
  tbody.classList.add("cal-tbody");

  tbe.appendChild(tbody);
  var week = 0;
  //tbody.appendChild(CreateWeakHeader("Week " + week));

  var tre = document.createElement('tr');

  for (var j = 0; j < data.length; j++) {


    if (j % 7 == 0) {
      week++;
      tbody.appendChild(CreateWeakHeader("Week " + week));





    }
    var thead = document.createElement('td');
    thead.classList.add("ui-droppable");


    thead.appendChild(data[j]);
    tre.appendChild(thead);


    tbody.appendChild(tre);





  }




  header3.appendChild(tbe);
  document.body.appendChild(header);


}

$("#tb").click(function() {
  var header = document.createElement("div");
  header.innerHTML = "test";
  var d = [header, header, header, header, header, header, header, header];
  htmlTable(d, days);


});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<button type="button" id="tb">CreateTable</button>

I'm trying to order the data that I get from my server to match the columns of my table. My table columns are days from Monday to Sunday. When my data has more than 7items it needs to separate with another td. The td shows me week 1 and when my data has more than 7 items it needs to separate again that shows week 2 etc.

Update

Im now using a snipped verdion of my code. Hope someone can help me out with this. Thank you

Heretic Monkey

There's a few things going on in the code that are problematic.

  1. An attempt to add the table cells to the row, and the row to the table, was made on each iteration of the for loop. That would have produced a lot of rows with single cells had it worked.
  2. It didn't work because there was only ever a single instance of tre, the row variable. So that meant the line tbody.appendChild(tre); did nothing, since appendChild won't append an element that already has a parent element.
  3. Because your data was an array of references to HTMLElements with parents, appending them using appendChild did nothing for the same reason.

I've amended the code below to take care of all of these situations.

Firstly, the code will append a clone of the data to the cell if it's an HTMLElement. I expect in your real code you won't need this, but for this example, why not? It then appends the cell to the row and continues to the next data element.

Secondly, when the data iterator is at 7, before it appends the "Week N" header, it appends a clone of the row, if it has cells on it.

Finally, after appending the clone of the row, the code will reset the row variable to a new instance of a tr element, with no cells.

I also made some variable name and formatting changes to your code just so I could more easily work with it.

function CreateWeakHeader(name) {
  var tr = document.createElement('tr');
  var td = document.createElement('td');
  td.classList.add("cal-usersheader");
  td.style.color = "#000";
  td.style.backgroundColor = "#7FFF00";
  td.style.padding = "0px";
  td.appendChild(document.createTextNode(name));
  tr.appendChild(td);

  var thh = document.createElement('td');
  thh.colSpan = "6"; // "31"; Why 31? A week has 7 days...
  thh.style.color = "#FFFFFF";
  thh.style.backgroundColor = "#7FFF00";
  tr.appendChild(thh);

  return tr;
}

function htmlTable(data, columns) {
  var header = document.createElement("div");
  header.classList.add("table-responsive");

  var header2 = document.createElement("div");
  header2.id = "calplaceholder";
  header.appendChild(header2);

  var header3 = document.createElement("div");
  header3.classList.add("cal-sectionDiv");
  header2.appendChild(header3);

  if ((!columns) || columns.length == 0) {
    columns = Object.keys(data[0]);
  }

  var tbe = document.createElement('table');
  tbe.classList.add("table", "table-striped", "table-bordered");
  var thead = document.createElement('thead');
  thead.classList.add("cal-thead");
  tbe.appendChild(thead);

  var tre = document.createElement('tr');
  for (var i = 0; i < columns.length; i++) {
    var the = document.createElement('th');
    the.classList.add("cal-toprow");
    the.textContent = columns[i];
    tre.appendChild(the);
  }

  thead.appendChild(tre);

  var tbody = document.createElement('tbody');
  tbody.classList.add("cal-tbody");
  tbe.appendChild(tbody);

  var week = 0;
  //tbody.appendChild(CreateWeakHeader("Week " + week));

  var tre = document.createElement('tr');
  for (var j = 0; j < data.length; j++) {
    if (j % 7 == 0) {
      week++;
      /* Major changes start here */
      // if the row has cells
      if (tre.querySelectorAll('td').length) {
        // clone and append to tbody
        tbody.appendChild(tre.cloneNode(true));
        // reset table row variable
        tre = document.createElement('tr');
      }
      // then append the Week header
      tbody.appendChild(CreateWeakHeader("Week " + week));
    }

    var td = document.createElement('td');
    td.classList.add("ui-droppable");
    // Set the value of the cell to a clone of the data, if it's an HTMLElement
    // Otherwise, make it a text node.
    var value = data[j] instanceof HTMLElement ?
      data[j].cloneNode(true) :
      document.createTextNode(data[j]);
    td.appendChild(value);
    tre.appendChild(td);
  }
  // If the number of data elements is not evenly divisible by 7,
  // the remainder will be on the row variable, but not appended
  // to the tbody, so do that.
  if (tre.querySelectorAll('td').length) {
    tbody.appendChild(tre.cloneNode(true));
  }

  header3.appendChild(tbe);
  document.body.appendChild(header);
}

$("#tb").click(function() {
  var header = document.createElement("div");
  header.innerHTML = "test";
  var d = [header, header, header, header, header, header, header, header];
  htmlTable(d, days);
});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button type="button" id="tb">CreateTable</button>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Dynamically created table cells not showing in Firefox 32.0

Dynamically created table is not showing again after removing

Python Selenium - I created Nested List to put table data but showing wrong items order

Show HTML Code for dynamically created table

Delay in display for dynamically created rows for table in HTML

Set dynamic data to dynamically created table in JQuery

Get Dynamically created table Data in React Row

Dynamically created grid not showing

Dynamically Created Layout not Showing

showing explode data in html table

AngularJS: Binding Data to Dynamically Created HTML

Dynamically created table only displays last appended table data

Table is not created as expected

How to change color of a HTML table (dynamically created) cell based on a value?

Javascript date comparison for dynamically created HTML table rows

Toggle html attribute contenteditable in php dynamically created table

How to edit dynamically created HTML table using StringBuilder

Parse JSON and bind to dynamically created rows and columns of HTML table

How to send a html table (created by JavaScript dynamically) to PHP page?

How to style html table (tr and td tags) created dynamically with Jquery

Single Row Selection on Dynamically created html table row

Reactjs - State changes not rendering in dynamically created html table

Why is my data not showing after I created a Pivot table?

Java Script Can't retrieve data from dynamically created table

dynamically created PHP array field not saving data in table using mysql

Showing sql data in HTML table using php

Jquery Table Data not showing properly on html

Adding data dynamically to HTML Table in PHP

Data on axis is not in expected order

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive