Home > Software engineering >  Javascript table append new row below column in loop
Javascript table append new row below column in loop

Time:01-15

I have table and need to set value from JS to th column.

It's working but now not working if I add this to each column time.

<tr><th>OK</th><th>NG</th><th>ST</th></tr>

The result should be like this: enter image description here

Any trick how to do that?

const anHour = 60*60*1000;
const getTimes = (start, end) => {
  const hours = [];
  for (let i = start, n = end.getTime(); i.getTime() <= n; i.setTime(i.getTime() anHour)) hours.push(`${String(i.getHours()).padStart(2,"0")}:00`);
  return hours;
};

let startDate = new Date(2023, 0, 14, 8, 0, 0, 0);
console.log(startDate);

let endDate = new Date(2023, 0, 14, 20, 0, 0, 0);

var timeList = getTimes(startDate, endDate);

for(var i=0; i<timeList.length; i  ) {
  var time = timeList[i];

  var element = `
    <th colspan="2">${time}</th>
  `;

  $(".wrapper .output-container table thead").append(element);
}
.wrapper .output-container table {
    width: 100%;
}

.wrapper .output-container table th {
    padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <table>
      <thead></thead>

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

CodePudding user response:

Try setting the time <th>s colspan="3" instead of 2, then add two <tr>s to the <thead>. In each loop iteration, add the time to the first one and the three labels to the second one.

const anHour = 60 * 60 * 1000;
const getTimes = (start, end) => {
  const hours = [];
  for (let i = start, n = end.getTime(); i.getTime() <= n; i.setTime(i.getTime()   anHour)) hours.push(`${String(i.getHours()).padStart(2,"0")}:00`);
  return hours;
};

let startDate = new Date(2023, 0, 14, 8, 0, 0, 0);
let endDate = new Date(2023, 0, 14, 20, 0, 0, 0);

var timeList = getTimes(startDate, endDate);
for (var i = 0; i < timeList.length; i  ) {
  var time = timeList[i];

  var element = $(`<th colspan="3">${time}</th>`);
  $("#times").append(element);
  $("#labels").append('<th>OK</th><th>NG</th><th>ST</th>');
}
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}

.wrapper .output-container table {
  width: 100%;
}

.wrapper .output-container table th {
  padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <table>
      <thead><tr id="times"><tr><tr id="labels"><tr></thead>
      <tbody></tbody>
    </table>
  </div>
</div>

  • Related