1

I'm trying to create a table like this in HTML

So far this is my table created with this code:

    function renderHead(div, start, end) {
    var c_year = start.getFullYear();
    var r_year = "<tr>";
    var daysInYear = 0;

    var c_month = start.getMonth();
    var r_month = "<tr>";
    var daysInMonth = 0;
    
    var r_event = "<tr>";

    var r_days = "<tr> <td id= 'event'> Eventi </td>";
    
    for (start; start <= end; start.setDate(start.getDate() + 1)) {

            if (start.getFullYear() !== c_year) {
                r_year += '<td colspan="' + daysInYear + '">' + c_year + '</td>';
                c_year = start.getFullYear();
                daysInYear = 0;
            }
            daysInYear++;

            if (start.getMonth() !== c_month) {
                r_month += '<td colspan="' + daysInMonth + '">' + months[c_month] + '</td>';
                c_month = start.getMonth();
                daysInMonth = 0;
            }
            daysInMonth++;

            r_days += '<td id="days">' + start.getDate() + '</td>'; //riga dei giorni numero
    }
    
    r_days += " <td id='tot'> Totale </td> </tr>";
    r_year += '<td colspan="' + daysInYear + '">' + months[c_month] + ' '+ c_year +'</td>'; //riga del titolo che indica il mese
    r_year += "</tr>";
    r_event +=  '<td id="norm">Normali</td><td id="diff"colspan="' + daysInYear + '">  </td></tr>'+
                '<tr><td>Straordinarie</td><td colspan="' + daysInYear + '">  </td></tr>'+
                '<tr><td>Ferie</td><td colspan="' + daysInYear + '">  </td></tr>'+
                '<tr><td>Malattia</td><td colspan="' + daysInYear + '">  </td></tr>'+
                '<tr><td>Permesso</td><td colspan="' + daysInYear + '">  </td></tr>'+
                '<tr><td>Smart Working</td><td colspan="' + daysInYear + '">  </td></tr>'+
                '<tr><td>Trasferta</td><td colspan="' + daysInYear + '">  </td></tr>'+
                '<tr><td>Assenza non retribuita</td><td colspan="' + daysInYear + '">  </td></tr>'+
                '<tr><td>Altro</td><td colspan="' + daysInYear + '">  </td></tr>';
    
    table = "<table id='tblData' border='1'><thead>" + r_year + r_days + "</thead><tbody>" + r_event + "</tbody></table>"; //riga dei giorni numero

    div.html(table);
}
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
renderHead($('div#table2'), new Date(firstDay), new Date(lastDay));

I created it in Javascript cause i needed to have an header build with every day of the months and online i found this solution. But know I'm struggling cause i dont' know how to create the empy cells in the middle.

I tried by adding it via CSS but doesnt work. This is how I call my table in HTML: <div id="table2" class="calendar"></div> And this is the class in CSS:

    div.calendar table tr td {
    border: 1px solid black;
    text-align: center;
    empty-cells: show;
    background-color: #D6EEEE
}
5
  • Would it not be better to create the table in html and then manipulating it with javascript? I'd recommend you read about html table structures as your first step. Commented Apr 6, 2022 at 15:01
  • I could be a possibility, but I dont know how to add dynamically every days of a month then Commented Apr 6, 2022 at 15:02
  • My table update its header every months (like now it has 30 days because April has 30 days, but next month it's gonna be 31 cells for the 31 days of May) Commented Apr 6, 2022 at 15:03
  • I'll give some advice. between each <tr></tr> you have <td></td>. each set of <td>'s are a cell. You need as many td's as days of the month. The issue with what you have provided is it's not flexible at all and any developer would probably throw it away and start again. Don't let this discourage you if you want to continue learning to program, but I suggest you start simpler and learn the basics. Stackoverflow isn't a free coding service, most of us just like to answer questions in our freetime. And many people try to abuse our generosity. Take care. Commented Apr 6, 2022 at 15:13
  • I really thank you for you advice, you are one of the few gentle ppl I met here. But I already know that. I was asking here because I'm new to JS and wanted to know if there was a way to not add manually as many <td> as many days. It's been 3 days since I'm bagging my head on this code for this thing. I wouldnt ask here if I havent tried before. What I post it's just the result of days of try Commented Apr 6, 2022 at 15:16

1 Answer 1

2

const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
//Start with an array of columns
let rowData = ["Normali", "Straordinarie","Ferie","Malattia","Permesso","Smart Working","Trasferta","Assenza non retribuita","Altro" ];
   
//Our render function
function renderTable($targetTable, date) {  

    //all we actually need is the number of days in a given month....
    let numberOfDaysInMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate(); // just get the last day

    //create the table header to display the month and date, and make is span all the days + the names column + the total column.
    let $tableHeader = $(`<tr><th colspan="${numberOfDaysInMonth+2}">${monthNames[date.getMonth()]} ${date.getFullYear()}</th></tr>`)

    //add header to our table
    $targetTable.find('thead').append($tableHeader);
    
    //Lets create a new empty table row to hold our heading and add our first column 
    let $header = $("<tr><td>Eventi</td></tr>"); //this is using jQuery's method to create. anything starting $() is jQuery
    
    //Build the header
    //We're starting from 1 and counting up to the number of days
    for(let i = 1; i <= numberOfDaysInMonth; i++) {
        let $dayCell = $(`<td>${i}</td>`); // create a day cell with our day of month number in it.
      $header.append($dayCell); // Now we append our new day cell to our header.
    }
    //now add the Total cell.
    $header.append($('<td>Totale</td>'));
    
    //now our header is built, let's add it to our table....
    $targetTable.find('tbody').append($header);
    
    // now lets work on those columns....
    //This iterates (loops) through each row.  the `rowText` variable is updated to the next value from our array each time.
    rowData.forEach(rowText => {
     
        //Create a new row and set our text
        let $row = $(`<tr><td>${rowText}</td></tr>`);
     
        //now Javascript introduced a very nice string repeater we can use for our remaining cells.
        //this basically copies the string 1 more, than the number of days, to cater for our Totale column
        let $cells = $('<td></td>'.repeat(numberOfDaysInMonth + 1)); 
     
        // add these new cells to our row.
        $row.append($cells);
      
      //add our new row to the table
      $targetTable.find('tbody').append($row);
      
    })
    
}
var date = new Date();
renderTable($('#Table'), date);
table {
  border-collapse: collapse;
}
td {
  border:1px solid #222;
  width:30px;
}
td:first-child {
  width:auto;
}
td:last-child {
  width:auto;
}
tbody th {
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="Table"> 
  <thead></thead>
  <tbody></tbody>
</table>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you so much! You saved me. I was bagging my head for days now. I was near the end of my project and with you now, I'm basically at it! You are very kind!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.