Search code examples
javascriptfor-loopwebcalendar

How can I generate horizontal JavaScript numbers so that they correspond to the days of the month


This can write out the number vertically but not horizontal and it doesn't give the 7 14 21 28 number breaks

const getDay = document.getElementById('days');
const getWeek = document.getElementById('week');
getWeek.innerHTML = '<tr><th>H</th><th>K</th><th>Sz</th><th>Cs</th><th>P</th><th>Sz</th><th>V</th></tr>';
for (let i = 1; i < 32; i++) {
  getDay.innerHTML += ' <tr><td id="' + i + 'day" class="days" onclick="open' + i + '()">' + i + '</td>';

  if (i == 7) {
    getDay.innerHTML += '</tr>';
  }
  if (i == 14) {
    getDay.innerHTML += '<tr></tr>';
  }
  if (i == 21) {
    getDay.innerHTML += '<tr></tr>';
  }

  if (i == 28) {
    getDay.innerHTML += '<tr></tr>';
  }
}
<table>
  <thead id="week"></thead>
  <tbody id="days"></tbody>
</table>


Solution

  • You cannot add tags without end tags to innerHTML. The browser immediately closes the tag

    Also you pushed the tr's in the wrong order. Close first, then open

    Lastly use an eventListener on the tbody to handle the clicks

    const open = dayNum => {
      console.log(dayNum);
    };
    const getDay = document.getElementById('days');
    const getWeek = document.getElementById('week');
    getWeek.innerHTML = '<tr><th>H</th><th>K</th><th>Sz</th><th>Cs</th><th>P</th><th>Sz</th><th>V</th></tr>';
    const dayArr = ['<tr>']; // start with a open row
    for (let i = 1; i < 32; i++) {
      dayArr.push('<td id="' + i + 'day" class="days">' + i + '</td>');
      if (i % 7  == 0) dayArr.push('</tr><tr>'); // close and open the row
    }
    getDay.innerHTML = dayArr.join('');
    getDay.addEventListener("click", (e) => {
      const tgt = e.target.closest('td'); // we clicked a cell
      if (!tgt) return; // leave if not a cell
      open(tgt.textContent);
    })
    <table>
      <thead id="week"></thead>
      <tbody id="days"></tbody>
    </table>