Adding up rows and columns using HTML

I've designed an HTML table to function as a spreadsheet, with the goal of being able to total up rows and display the sum in a cell labeled "Total." The same calculation should be applied to columns as well, with totals displayed in the last column cell. I've attempted various jQuery implementations without success. Here's the structure of the table:

  <!-- Table Content Starts Here -->
    <div class="tableContent">

        <div class="row">

            <div class="col-md-12">
                <table id="ccTable" cellpadding="0" cellspacing="0" border="1" class="table table-striped table-bordered table-hover">
                    <thead>
                        <tr class="tableHdr">
                            <th scope="col" align="right">Days</th>
                            <th scope="col">S</th>
                            <th scope="col">M</th>
                            <th scope="col">T</th>
                            ...
                                                    <td><input type='text' size ="2"class='editable' value='0.00' /></td>
                        </tr>

Answer №1

It seems like you're looking to calculate the sum of values in both rows and columns of a table. Here's a sample code that can help you achieve this:

$(document).ready(function() {
  var row = 0,
    col = 0,
    ncol = 0;
  var sum;
  // sum by row
  $("tr").each(function(rowindex) {
    sum = 0;
    col = 0;
    $(this).find("td").each(function(colindex) {
      col++;
      newval = $(this).find("input").val();
      if (isNaN(newval)) {
        $(this).html(sum);
        if (col > ncol) {
          ncol = col - 1;
        }
      } else {
        sum += parseInt(newval);
      }
    });
  });

  // sum by col
  for (col = 1; col < ncol + 1; col++) {
    sum = 0;
    $("tr").each(function(rowindex) {
      $(this).find("td:nth-child(" + col + ")").each(function(rowindex) {
        newval = $(this).find("input").val();
        if (isNaN(newval)) {
          $(this).html(sum);
        } else {
          sum += parseInt(newval);
        }
      });
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input value="4" />
    </td>
    <td>
      <input value="2" />
    </td>
    <td>
      <input value="3" />
    </td>
    <td class="rowsum">-</td>
  </tr>
  <tr>
    <td>
      <input value="4" />
    </td>
    <td>
      <input value="5" />
    </td>
    <td>
      <input value="6" />
    </td>
    <td class="rowsum">-</td>
  </tr>
  <tr>
    <td>
      <input value="7" />
    </td>
    <td>
      <input value="8" />
    </td>
    <td>
      <input value="9" />
    </td>
    <td class="rowsum">-</td>
  </tr>
  <tr>
    <td class="colsum">-</td>
    <td class="colsum">-</td>
    <td class="colsum">-</td>
  </tr>
</table>

Answer №2

To retrieve the values from each cell, you can include event listeners like change, keyup, and input on the input fields within the table.

Important: Ensure that the total inputs are not editable.

$(function() {

  // Add an event listener
  $('#ccTable input').bind("change keyup input", function() {

    var colValues = [];                                        // Initialize the column array

    $('#ccTable tbody tr:not(:last-child)').each(function() {  // Iterate through each row
      var rowValues = 0;                                       // Initialize row total
      $(this).find('input:not(:last)').each(function(i) {      // Loop through each input in the row
        var val = +$(this).val() || 0;                         // Retrieve input value, if not a number assign as 0

        rowValues += val;                                      // Add input value to rowValues 

        colValues[i] = colValues[i] || 0;                      // Initialize the column as 0
        colValues[i] += val;                                   // Add input value to the column
      })

      // Update row total
      $(this).find('input:last').val(rowValues.toFixed(2));
    });

    // Update column total
    $('#ccTable tbody tr:last-child').find('input:not(:last)').each(function(i) {
      $(this).val(colValues[i].toFixed(2));
    })

    // Calculate sum of all colValues and update the total/total cell
    var sum = colValues.reduce((c, v) => c + v);
    $('#ccTable tbody tr:last-child').find('input:last').val(sum.toFixed(2));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="ccTable" cellpadding="0" cellspacing="0" border="1" class="table table-striped table-bordered table-hover">
  <thead>
    <tr class="tableHdr">
      <th scope="col" align="right">Days</th>

      ... (remaining HTML code)
      
    </tr>
  </thead>
  <tbody>
  
    ... (remaining HTML code)
    
  </tbody>
</table>

Answer №3

Take a look at my Sample code

This code snippet is concise and straightforward.

calculateTable('#ccTable');

function calculate(table, e) {
  return setTimeout(()=>{
    var $rows = $(table).find('tr');

    var data = $rows
    .slice(2,-1)
    .get()
    .map(el =>
         $(el)
         .find('td:not(:first) input')
         .get()
         .map(el => parseFloat($(el).val()) || 0)
        );

    $rows.last()
      .find('td')
      .slice(1)
      .each((index, el) => {
            $(el).find('input')
                .val(data
                    .reduce((acc, val) => acc + val[index], 0)
                .toFixed(2));
        });
  });
}

function calculateTable (target) {
    handler = calculate.bind(null, target)
    $(target).find('input')
            .change(handler)
            .keypress(handler);
  handler();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display a block by using the focus() method

My objective is : To display a popin when the user clicks on a button To hide the popin when the user clicks elsewhere I previously implemented this solution successfully: Use jQuery to hide a DIV when the user clicks outside of it However, I wanted to ...

When viewed on mobile devices, the image shrinks significantly

I'm experiencing an issue where the image shrinks significantly when viewed on a mobile device or when zooming in the browser. Can you help me understand why this is happening and suggest a solution? Here are the HTML and CSS code snippets: HTML < ...

Circular Graphical Representation using CSS3 styling

Check out my latest creation - a donut chart: http://jsfiddle.net/4azpfk3r/217/ I'm trying to customize the appearance of the donut chart. Is there a way to give it a red outline and have the filled score/percentage in solid red, while leaving a tran ...

JavaScript cannot determine the length of an array of objects

I'm encountering an issue with an array of objects named tagTagfilter. When I log it in the browser, it doesn't immediately show the correct length value inside. tagTagFilter: TagFilter = { filterName: 'Tag', tags: [] ...

Sending both GET and POST parameters in a single AJAX request using jQuery

Is it possible to send both GET and POST parameters in a jQuery AJAX request at the same time? I have attempted to append do=ajax&id=" + ID to the url, but the resulting request only includes sss.php without the query string (GET part). Any suggestion ...

Issue with uneven spacing on both ends of the screen on mobile devices

I have successfully used a <div style="margin:0 auto; "> tag with the specified property, working perfectly. However, I added another <div> above and set the float as follows: .gallery-div{ background:url(images/gallery-bg.png) repeat-y; ...

Installing different versions of a package in npm can be done by loading multiple versions

I am in the process of setting up a web API and I want to provide support for various versions of the underlying library. In essence, I would like to access it through: where x.y.z represents the version of the library I am utilizing. Using npm for mana ...

Increasing the level of CSS list counters

HTML <ol> <li>item1 <ol> <li>item2</li> </ol> </li> <li>item1 <ol> <li>item2</li> <li>item3</li> </ol> </li> </ol> SC ...

What is the best way to retrieve AJAX data in Django views?

I am currently facing difficulties with retrieving data from an AJAX call in my Django views using the GET method. Unfortunately, I am encountering issues accessing the data within my views and the console.log statements are not showing any output. As a ne ...

Obtain the child's identification number and include it in the parent element as an ARIA

I need assistance with a JavaScript (or jQuery) function to dynamically add an 'aria-labelledby' attribute to parent <figure> elements based on the ID of the <figcaption>. I have multiple images and captions set up in <figure>&l ...

Attempting to craft a multi-filter feature using AngularJS that will allow for the precise filtering of JSON data based on both month and year identifiers

I have integrated AngularJS into the RoR framework and am working on creating a multi-filter for the "ng-repeat" function to filter JSON data based on "month_id" and "year_id". Here is the current code: JSON: [ { "date":"October 4, ...

What is the best way to position a background image at the top of a div without overlapping the

I have this HTML code: <div class="page"> <div id="header"> ... </div> </div> Below is my CSS: .page { width: 1028px; background-color:#103250; margin-left: auto; margin-right: auto; } ...

Toggle the class of an element with jQuery based on the unchecked state of a radio button

I have been working on a script to replace form elements with styled divs, but I am facing a challenge with radio buttons. I am struggling to remove the "selected" class from one button when another button is selected. You can find the code in this fiddle ...

Adjusting the styling of a webpage in real-time

Here is the CSS code I am working with: .myTabs .JustForFun .ajax__tab_inner:hover { width: 109px; background: url ("/images/csc_tr.png") no-repeat 100% 0%; margin-right: 2px; background-color: #BBC614; } I want to change the background-c ...

What exactly does the question mark represent in the code structure as indicated in VSCode?

When looking at the image, you can see that in the description of done(), VSCode indicates the type of parameters using a colon error: any or sometimes with a question mark and colon user?: any. So, what exactly is the distinction between these two ways o ...

Setting up numerous instances of TinyMCE for use

I am having trouble initializing two instances of tinymce on my webpage. Even after following the guidance provided in this particular thread, I am unable to get it working. Could it be possible that I need to introduce a timeout between initializing the ...

An error occurred with the authorization headers when attempting to retrieve the requested JSON

I am attempting to retrieve JSON data from the Bing Search API. Here is what I have implemented: <!DOCTYPE html> <html> <body> <p id="demo"></p> <script language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"& ...

Why is it that jQuery is not working in Internet Explorer but works fine in Firefox?

Below is the code for handling file upload onchange event: <input type='file' onchange="displayFilePath(this);" id="loadfile" /> This text field will display the full path of the uploaded file. <script type="text/javascript"> fun ...

Customize the appearance of polygons in OpenLayers 2 by adjusting the fill color and opacity

I am aiming to use different fill colors and opacity values for various shapes (such as Triangle, Circle, Square, Hexagon, etc.). Although I can draw the shapes, set different titles, and stroke colors with the code below, I'm struggling to define th ...

After reloading the data tables, analyze the information and dynamically highlight any rows in red that remain unchanged

I have a table that is refreshed every 5 minutes using ajax.reload(). One of the rows in this table is labeled as CIP. My goal is to highlight the CIP row on each refresh where the value remains unchanged from the previous value (value received in the la ...