JavaScript calculations are not functioning as anticipated

I am encountering an issue with a gridview that contains a row where integer values, such as 7000, are being added.

My goal is to calculate the total of all these rows and display it in a textbox after 2-3 rows have been added.

To achieve this, I have implemented the following code snippet:

if (document.getElementById('txtTotalExp').value == "") {
            var Expense = 0;
        } else {
            var Expense = document.getElementById('txtTotalExp').value;
        }
        for (var i = 0; i < GridExpInfo.Rows.length; i++) {
            var totAmount = GridExpInfo.Rows[i].Cells[7].Value;
            var totval = totAmount;
            Expense += parseInt(totval);
        }

document.getElementById('txtTotalLandVal').value = parseInt(TotalPayableValue) + parseInt(Expense);

However, when checking the textbox, I am seeing a result like 200010001512.

It seems that the addition operation is not functioning correctly.

Answer №1

Upon reviewing your inquiry, it seems that you are dealing with a tabular structure containing rows of values. Your objective is to compute the sum for each row and then obtain the total sum of all these individual row sums within the entire table.

I aimed to present a functioning code snippet as a demonstration of how to tackle this issue. However, since not all the essential code components were provided, I improvised some sections. In the process, I introduced an alternative method, which could be considered more contemporary, for resolving the overarching problem you appear to be addressing. While this may extend beyond your initial query (...though some of the other responses discussing parseInt might address your immediate concern), my intention is to offer additional insights.

Below is an illustration showcasing the implementation using various modern JavaScript functionalities. The accompanying comments have been included to elucidate the operations at each stage comprehensively, allowing for a better understanding of the logic involved. To delve deeper into grasping each step, further exploration into mastering JavaScript would be beneficial. A recommended resource is the Mozilla Developer Network (MDN), offering comprehensive documentation on these features.

// Upon clicking the button, execute the following actions...
document.querySelector('button').onclick = () => {

  // Calculate the total sum across the table
  const rowSums =

    // Obtain a nodeList of all table rows in the document
    // and convert the array-like nodeList into an actual array
    // comprising table row elements
    [...document.querySelectorAll('tr')]

      // Exclude the first row, which represents the column headers
      .slice(1)

      // Create a new array from the original table rows (excluding the first row)
      // where each element is derived based on the respective table row from the original array
      .map(row => {

        // Compute the sum of values within the specific row
        const rowSum =

          // Retrieve a nodeList of all table cells in the row
          // and transform the array-like nodeList into an actual array
          // consisting of table cell elements
          [...row.querySelectorAll('td')]

            // Omit the last cell, representing the one holding the final sum for this row
            .slice(0,-1)

            // From the array of table cells within this row (excluding the last one)
            // derive a single value by progressively performing a task for each cell
            .reduce(

              // For every table cell within this row, retain the cell itself
              // along with the accumulating value being generated gradually through all
              // cells in the row, essentially representing the sum of all values within this row
              (accumulatingRowSum, cell) =>

                // Add the numerical value of the current cell to the sum of values being accumulated
                // throughout this row for each cell
                accumulatingRowSum + parseInt(cell.innerHTML, 10),

              // Initiate the cumulative sum of values within this row from zero
              0
            );

        // Retrieve all cells within this row
        const rowCells = row.querySelectorAll('td');

        // Populate the last cell of the row with the sum of values from this row
        rowCells[rowCells.length - 1].innerHTML = rowSum;

        // Insert the sum of values within this row into the growing array
        // encompassing all such values for all rows
        return rowSum;
  });
  
  // Determine the total sum for the entire table
  const totalExpenses =

    // Commence with the array of individual row sums
    rowSums

      // Similar to the previous `reduce` operation, aggregate the array of multiple row sums
      // into a solitary figure representing the overall total sum obtained by adding up
      // all individual row sums, initiating from zero
      .reduce((accumulatingTotalSum, rowTotal) => accumulatingTotalSum + rowTotal, 0);

  // Place the final sum within the designated span element
  document.querySelector('#txtTotalExp').innerHTML = totalExpenses;
};
table {
  border: solid black 1px;
  border-collapse: collapse;
}
th, td {
  border: solid black 1px;
  padding: 0.5em;
}
<table>
  <tr><th>Column 1</th><th>Column 2</th><th>Row Total</th></tr>
  <tr><td>3500</td><td>1200</td><td></td></tr>
  <tr><td>2700</td><td>4500</td><td></td></tr>
  <tr><td>3100</td><td>1300</td><td></td></tr>
</table>
<p>The total expenses amount to: <span id="txtTotalExp"></span></p>
<button>Calculate</button>

Answer №2

Here is the code snippet you can utilize:

let sum = parseInt(TotalPayableValue, 10) + parseInt(Expense, 10);
    document.getElementById('txtTotalLandVal').value = sum;

Answer №3

Check out this solution:

let totalExpense = 0;
if (document.getElementById('txtTotalExp').value !== "") {
 let expense = parseInt(document.getElementById('txtTotalExp').value);
}
for (let i = 0; i < GridExpInfo.Rows.length; i++) {
 let totalAmount = GridExpInfo.Rows[i].Cells[7].Value;
 totalExpense += parseInt(totalAmount);
}

The issue at hand is that the initial value of 'totalExpense' might be a string. Have you attempted to see if setting it as "totalExpense = 0" resolves the error?

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

Has anyone here had the opportunity to work with the @material-ui/pickers Calendar API before?

I'm seeking clarification on this matter because there seems to be a lack of guidance on its usage. The documentation doesn't provide any examples aside from listing the props available: Thus far, I've constructed my Calendar component usin ...

Resolving Null DateTime Property in MVC Model Through Ajax Post

While working on an ajax POST request with Model, everything seemed to be functioning well except for one datetime property. Upon inspecting the network tab in the browser, I noticed that all values were being passed in the request payload as expected. How ...

I am looking to display multiple divs sequentially on a webpage using JavaScript

Looking to display a rotating set of alerts or news on my website. The goal is to show each news item for a certain number of seconds before moving on to the next one in line. However, I'm new to javascript and need help creating a code that will cont ...

Organize Javascript objects based on their dates - group them by day, month,

I've scoured the internet for examples but haven't found a suitable one that accomplishes the simple task I need. Maybe you can assist me with it. Here is an array of objects: [ { "date": "2015-01-01T12:00:00.000Z", "photoUrl": "", ...

Is there a way to make a jQuery dialog function similarly to a JavaScript alert box?

The topic of replacing the standard 'alert' with a customized jQuery dialog has been discussed before, as seen in this thread: Custom alert and confirm box in jquery In that conversation, Hemant Malpote pointed out that: "But it [the suggested ...

Can you explain the distinction between postMessage() and dispatchEvent() in relation to the origin policy?

Here is some code that I wrote. I tried setting the MessageEvent's origin to *, but I'm still getting an error in the console saying "Blocked a frame with origin "AAAA" from accessing a frame with origin "BBBB". Protocols, domains, and ports must ...

How to retrieve a JSON item without knowing the name of the parent key

When requesting JSON from Wikipedia's API, the URL is: http://en.wikipedia.org/w/api.php?action=query&prop=description&titles=WTO&prop=extracts&exsentences&explaintext&format=json This is how the response is structured: { ...

Trouble with filtering in the Bootstrap table control feature

Incorporating the Filter Control extension with my bootstrap table is my goal. On the server side, I am utilizing django as the framework. The necessary CSS and JS files that I have included are: {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_jav ...

Put a pause on running a JavaScript function until the one preceding it has completed

After successfully creating a product using a modal box form on my page, the modal disappears with an effect and the list of products on the page should be updated with the newly added item. However, the animation of the modal disappearing disrupts the fl ...

Is it possible to simultaneously send a JSON object and render a template using NodeJS and AngularJS?

I'm currently facing issues with my API setup using NodeJS, ExpressJS Routing, and AngularJS. My goal is to render a template (ejs) while also sending a JSON object simultaneously. In the index.js file within my routes folder, I have the following s ...

Perform calculations using the corresponding data table within the model

I am looking to perform tax calculations directly within the model using two specific models: UST and Buchungen. Model 1: UST public partial class Ust { public Ust() { Buchungen = new HashSet<Buchungen>(); } public int Id { ...

Eliminating identical characters shared between two strings

I am looking to eliminate any characters that match between two strings. For example: string str1 = "Abbbccd"; string str2 = "Ebbd"; From these strings, I want the output to be: "Abcc", where only the matching characters present in both str1 and str2 ar ...

Is it true that one line arrow functions cannot include a semicolon without braces?

As someone who is new to React and ES6 syntax, I stumbled upon an interesting observation. When I wrote the following code snippet: return <input onChange={event => console.log(event.target.value);} />; I encountered a "Cannot find module" error ...

Encountering an error while attempting to integrate react-router with react-transition-group: "Invalid element type specified..."

Currently, I am attempting to utilize the CSSTransition component from the react-transition-group module in order to create smooth page transitions when a user moves from one route to another. After running the code below, I encountered the following error ...

Vue is refusing to display information for a certain API call

Within my next component, I have the following structure: <template> <div class="home"> <div class="container" v-if="data" > <Card v-for="result in data" :img="result.links[0]&q ...

Is the global.asax file compatible with DotNet class library projects?

Is it possible to utilize the Global.asax file in .NET Class Library projects? I have not found any information specifying that the Global.asax file is only meant for use with Web applications. The code within the Global.asax file is compiled and invoked ...

A guide on utilizing a function import within an exported function within ReactJS

As a beginner in React, I have been exploring Named and Default Exports, but I encountered a problem that I am having trouble articulating. Below is the code that is causing confusion: namedExport.js const name = "xyz"; const age = 20; const my ...

Encountering problem: 'Dom7 is undefined' while initializing a Framework7 - Vue application using Webpack

Initially, I followed the steps outlined on the official website: cloning the repository, installing node dependencies, and running the application. However, upon executing the npm run dev command, an error was encountered when trying to open the app in th ...

Having issues with jQuery animation not working correctly?

Here is the code snippet I am working with: function move() { $(document).mousemove(function(e){ var x = e.pageX; $('.linkHover').animate({'right': '=' + x + 'px'}, 'slow'); }); ...

Preventing Angular $rootElement.on('click') from affecting ReactJS anchor tag interactions

Running both AngularJS and ReactJS on the same page has caused an issue for me. Whenever I click on a ReactJS <a> tag, Angular's $rootElement.on('click) event is triggered and the page redirects. I need to perform some functionality in Re ...