Home > database >  Get sum of cells in a row Javascript
Get sum of cells in a row Javascript

Time:04-09

My problem is: I'm building this table* and I need to get the total of each row. My table works with Fullcalendar and fecth events from database.

This is my table*:

table

whats it does is basically fetch the events in my calendar and print it here with the corresponding event, the total amount of hours and in the corresponding day.

And this is the code of how I build it till this point (with some help from internet and gentle ppl here on SO):

 let rowData = [    "<tr class='norm'><td>Normali</td></tr>", 
                "<tr class='stra'><td>Straordinarie</td></tr>",
                "<tr class='fer'><td>Ferie</td></tr>",
                "<tr class='mal'><td>Malattia</td></tr>",
                "<tr class='per'><td>Permesso</td></tr>",
                "<tr class='sm'><td>Smart Working</td></tr>",
                "<tr class='tra'><td>Trasferta</td></tr>",
                "<tr class='anr'><td>Assenza non retribuita</td></tr>",
                "<tr class='alt'><td>Altro</td></tr>" ];
   
//____________________inserisce nella tabella l'header coi giorni del mese___________________________________________________
function renderTable($targetTable, date) {  

    //calcola il numero dei giorni nel mese (30/31/28)
    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}" style="text-align: center;">${months[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>"); //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  style="width: 10%;">${i}</td></tr>`); // 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 id="tot">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 = $(`${rowText}`);
     
        //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 id="hou" ></td>'.repeat(numberOfDaysInMonth)   '<td id="totNum"></td>'); 
     
        // 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($('#table2'), date);
    
//____________________inserisce nel corpo della tabella gli eventi___________________________________________________
function getEvents(year, month, data){
    $('#printEvents').modal('show');
    var date = new Date();
    var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
    var lastDay = new Date(date.getFullYear(), date.getMonth()   1, 0);
    var table = document.getElementById('table2');
    var currentEvents = $('#calendar').fullCalendar('clientEvents').filter(event => (new Date(event.start) > firstDay && new Date(event.end) <= lastDay));
    let DaysInMonth = new Date(date.getFullYear(), date.getMonth()   1, 0).getDate();
    
    //calcola la differenza di ore tra start e end di ogni evento
    for(i=0; i<currentEvents.length; i  ) {
        if(currentEvents[i].nomeUtente == $("#nomeUtente").data('value')){
            const start = new Date(currentEvents[i].start._i);
            const end = new Date(currentEvents[i].end._i);          
            //eventi Normali/Ferie/Malattia toglie 1.30h in millesecondi
            if (currentEvents[i].title == "Normali" || currentEvents[i].title == "Ferie" || currentEvents[i].title == "Malattia"){ 
                const milliseconds = Math.abs((end - start) - 5400000);
                var hours = milliseconds / 36e5;
            }else{
                const milliseconds = Math.abs(end - start);
                var hours = milliseconds / 36e5;            
            }
            
            //identifica posizione celle Totale di ogni evento
            if(DaysInMonth == '30'){
                var totNum = '31';
            }else if(DaysInMonth == '31'){
                var totNum = '32'
            }else if(DaysInMonth == '28'){
                var totNum = '29'
            }else if(DaysInMonth == '29'){
                var totNum = '30'
            }
            
            //determina il giorno del mese della data
            const d = new Date(currentEvents[i].start);
            let day = d.getDate();
            
            
            //assegna ad ogni riga evento il tot di ore che gli appartiene
            var norm = $(".norm").find("td:eq(0)").text();
            var stra = $(".stra").find("td:eq(0)").text();
            var fer = $(".fer").find("td:eq(0)").text();
            var mal = $(".mal").find("td:eq(0)").text();
            var per = $(".per").find("td:eq(0)").text();
            var sm = $(".sm").find("td:eq(0)").text();
            var tra = $(".tra").find("td:eq(0)").text();
            var anr = $(".anr").find("td:eq(0)").text();
            var alt = $(".alt").find("td:eq(0)").text();
            
            //riga Normali
            if (currentEvents[i].title == norm){
                var time = $('#table2 >tbody').find('tr:eq(1) > td:eq(' day ')');//trova la cella n nella rica di 'Normali'
                $(time).text(hours);
                
            }
            //riga Straordinarie
            else if (currentEvents[i].title == stra){
                var time = $('#table2 >tbody').find('tr:eq(2) > td:eq(' day ')');
                $(time).text(hours);
                
            }
            //riga Ferie
            else if (currentEvents[i].title == fer){
                var time = $('#table2 >tbody').find('tr:eq(3) > td:eq(' day ')');
                $(time).text(hours);
                 
            }
            //riga Malattia
            else if (currentEvents[i].title == mal){
                var time = $('#table2 >tbody').find('tr:eq(4) > td:eq(' day ')');
                $(time).text(hours);
                
            }
            //riga Permesso
            else if (currentEvents[i].title == per){
                var time = $('#table2 >tbody').find('tr:eq(5) > td:eq(' day ')');
                $(time).text(hours);
                
            }
            //riga Smart Working
            else if (currentEvents[i].title == sm){
                var time = $('#table2 >tbody').find('tr:eq(6) > td:eq(' day ')');
                $(time).text(hours);
                
            }
            //riga Traferta
            else if (currentEvents[i].title == tra){
                var time = $('#table2 >tbody').find('tr:eq(7) > td:eq(' day ')');
                $(time).text(hours);
                
            }
            //riga Assenza non Retribuita
            else if (currentEvents[i].title == anr){
                var time = $('#table2 >tbody').find('tr:eq(8) > td:eq(' day ')');
                $(time).text(hours);
            
            }
            //riga Altro
            else if (currentEvents[i].title == alt){
                var time = $('#table2 >tbody').find('tr:eq(9) > td:eq(' day ')');
                $(time).text(hours);
                
            }
      }
  }
};

I tried this:

$('tr').find('td:last').text(function() {
            return $(this).siblings().map(function() { return parseInt($(this).text(), 10); }).get().reduce(function(x, y) { return x   y; });
    })

this:

$('#table2 tr.norm td#hou.count').each(function(){
            var $td = $(this);  

            var colTotal = 0;
            $('#table2 tr:not(:first,.totNum)').each(function(){
                colTotal   = parseInt($(this).children().eq($td.index()).html(),30);
            });

            $('#table2 tr.totNum').children().eq($td.index()).html('Total: '   colTotal);
        });

I tried every kind of function but I'm not gettin how to do that because i'm new to Javascript and Jquery so I'm actually lost and the moment, if someone can help me it will be very kind


I wrote this(reference to the Normali row):

$('#table2 tr:eq(2)').find('td:last-of-type').text(function() {
            return $(this).siblings().map(function() {
                return parseInt($(this).text(), 30);
            }).get().reduce(function(x, y) {
                return x   y;
            });
        })

As i wrote in the comment it's giving me NaN in the cell of total

CodePudding user response:

Your issue with $('tr').find('td:last') is that this finds all the trs then gets the one last one, across all of them.

Change to

$("tr").find("td:last-of-type")

or

$("tr").find("td:last-child")

Example snippet:

$('tr').find('td:last-child').text(function() {
  return $(this).siblings(".count").map(function() {
    return parseInt($(this).text(), 10);
  }).get().reduce(function(x, y) {
    return x   y;
  });
})
td:last-of-type { font-weight:bold; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr><td>Row 1</td><td class='count'>1</td><td class='count'>2</td><td></td>
<tr><td>Row 2</td><td class='count'>2</td><td class='count'>3</td><td></td>
<tr><td>Row 3</td><td class='count'>3</td><td class='count'>4</td><td></td>
</tbody>
</table>

  • Related