Combine multiple form values to calculate the total sum

To tackle the issue of adding up independent totals in a PHP foreach loop and displaying a grand total, we need to modify the JavaScript function. Right now, the function works fine for each line, but doesn't calculate the grand total correctly. Let's figure out how to save the amounts separately and then sum them up to get the desired result. The goal is to have the grand total update dynamically whenever the quantity changes, just like the individual amounts do.

<head>
<script type="text/javascript">
function update(iteration){

var qty = document.getElementById('qty_' + iteration).value;
var price = document.getElementById('price_' + iteration).value;
price = price.substring(0, 7);
qty = parseInt(qty);

var amount = (qty * price).toFixed(2) ;
parseFloat(document.getElementById('amount_' + iteration).value = amount).toFixed(2);

var subtotal = 0;
for(var i =1; i < itemCount; i++) {
subtotal += parseFloat(document.getElementById('amount_' + i).value);
}

var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total $"+parseFloat(subtotal);

}
</script>
</head>

<?php
$listitems = unserialize($row["products"]);
$i=1; 
foreach($listitems as $item)
{
echo '<tr><td>'.$item["code"].'</td><td><input type="number" id="qty_'.$i.'" name="qty_'.$i.'"  min="1" size="3" value="1" onChange="iteration = '.$i.'; update(iteration); " /></td>';
echo '<td><input type="hidden" name="price_'.$i.'" id="price_'.$i.'"  value="';
echo $item['price'];
echo '" />';
echo $item['price'];
echo '</td><td><input type="text" name="amount_'.$i.'" id="amount_'.$i.'" size="6" readonly value="';
echo $item['price'];
echo '"/></td></tr>';
$i++;
}
?>

<div id="totalPrice"></div>

Answer №1

A few things stand out as I review the code.

It's important to include a radix parameter when using parseInt( ).

parseInt(qty, 10);

I'm puzzled by this particular line:

parseFloat(document.getElementById('amount_' + iteration).value = amount).toFixed(2);

The function parseFloat returns a floating point number, but it seems like you're not assigning it to anything.

The issue causing the error lies in the declaration of var subtotal.

You've essentially declared a variable to be equal to amount + itself, which is undefined at that point. What value are you intending for subtotal to have?

Update: Now that you made changes, the goal is to iterate through the items and sum them up.

var subtotal;
for(var i = 0; i < itemCount; i++) {
  subtotal += document.getElementById('amount_' + i).value;
}

This loop will go through 0 to the total number of items for the amount elements calculation.

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

The presence of foreign collections does not appear to be reflected in the combined data

I am developing a basic forum and I'm looking to connect two databases so I can show information about the user who created a post on that post: User.js: _id:60ccb13a21d65f0c7c4c0690 username: testuser name: test And Createpost.js _id:60d80b1305dcc5 ...

What are some strategies for efficiently displaying a large amount of data on a screen using Javascript and HTML without sacrificing performance?

Imagine having a hefty 520 page book with over 6,200 lines of text ranging from 5 to 300 characters each. The challenge lies in efficiently displaying this content on the screen for users to read without causing lag or performance issues. Attempting to re ...

Unable to find any matches when conducting a search through Google Apps Script

After spending days analyzing the code, I am encountering an error that states "uncaught reference error: google is not defined." This issue seems to occur specifically in line 360. Curiously, when inspecting the original code editor, line 360 simply conta ...

Is it allowed to use an ID as a variable identifier?

One method I often use is assigning a variable with the same name as the id of an element, like this: randomDiv = document.getElementById("randomDiv"); randomDiv.onclick = function(){ /* Do something here; */ } randomDiv.property = "value"; This tech ...

Angular promise fails to resolve after an extended period of waiting for a response

My application is designed to send GET requests to my node/express server. In order to monitor changes in the server code, I have implemented a setTimeout function. While the promise function on the client side initially functions properly for a short peri ...

Incorporate my personalized icons into the button design of ionic 2 actionSheet

I'm struggling to figure out how to incorporate my personal icon into the actionSheet feature of ionic 2/3. presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Mode', buttons: [ { ...

Mongodb/mongoose encountering issues with saving data only once, resulting in a 500 error

When I send json to my node.js/express app, it successfully receives the data and performs the desired action, but only once. After starting the appjs for the first time, it returns a 200 response code and saves the data to my mongodb. However, any subsequ ...

Updating HTML5 localStorage value upon a click

Currently, I have implemented a countdown timer using the provided code snippet. To prevent the count from resetting upon page refresh or reload, I am utilizing local storage. However, if there is an alternative solution to achieve this functionality, I wo ...

Deleting a li element within an AJAX response function can be accomplished by targeting the specific

I am attempting to remove the li element that is the parent of the clicked a element. Here is the code I am using: function vanish(id_arg){ $.ajax({ url: "/vanish/", type: "POST", data: {id_to_delete: id_arg}, ...

Unable to disable webpack HMR

I have set up my project using express version 4.14.0, webpack version 1.14.0 with babel and its presets. I obtained this sample webpack configuration from a reliable source: var path = require('path'); module.exports = { entry: './main. ...

Updating Django database records with ajax

I'm currently working on a feature that involves filtering table data and updating the table using ajax. Here's what I have so far: Filter Form: <form id="search" method="POST" action="{% url 'article-filter' %}"> <input ...

Is it advisable to prevent Set and Map from having unspecified generics in TypeScript?

Upon reviewing some old code that I wrote, I realized that I had neglected to specify a generic type for a Set. The type was set as Set<unknown>. Strangely, despite this, I found that I could still utilize all the methods of the Set without encounter ...

Avoid activating ng-blur when ng-keydown is triggered in AngularJS

Currently, I am working on a project involving angularJS and I am facing an issue with the execution of ng-blur conflicting with ng-keydown. The problem arises because ng-keydown causes the element to lose focus at a certain point. The HTML code in questi ...

Utilizing a function as a value in React state (setState) compared to defining state with constructor in a class and utilizing a state object

Can someone help me understand the concept of state in React better? I'm confused about the differences between these two implementations: This: class Todo extends ... { constructor (){ super() this.state = { ... } } } And This: class Todo extend ...

Utilizing jquery.validate.min.js for efficient form validation

Here is my JavaScript validate function: $("form[id='form']").validate({ Name: "required", submitHandler: function() { formSubmit(); } }); Not only do I wa ...

How to deactivate an option in md-autocomplete

I encountered a scenario where I converted an md-input-container with a md-select/md-option to a md-autocomplete. While in the initial setup of md-select/md-option, we were able to apply ng-disabled property to both the md-select and md-option. However, wh ...

Adding or removing a class using Jquery based on the condition of form validation

I am facing a problem with the following code that adds and removes classes to bring the next stage of the form. The form progresses step by step where certain fields need to be filled before validation on the next button, followed by filling other fields. ...

Improving React code by using conditional statements such as IF and Else

Currently, I am delving into the world of React and have managed to devise some logic for rendering a DIV. However, upon reflection, it has become evident that there is redundancy present in my code structure and I am uncertain about how to efficiently ref ...

Troubleshooting problem in Java related to encoding with XMLHttpRequest

Currently, I am utilizing XMLHttpRequest for an ajax call to my server. Let's consider the call: http = new XMLHTTPRequest(); var url = "http://app:8080/search.action?value=ñ" http.open("GET",url,true); http.setRequestHeader("Content-type", "applica ...

Leveraging both closetag.js and closebrackets.js simultaneously in Codemirror on a single line

Currently, I am integrating the Codemirror library with a textarea to enable autoclosing of HTML tags and brackets such as {}, (), []. However, I have come across an issue where they do not work together on the same line. For example, when typing out a ta ...