What is the correct method for calculating the sum of one input field and multiple output fields?

I have a single input field and multiple calculated output fields using JavaScript :Click here to view the screenshot of the calculated problem

You can see the live preview on this link: . When you visit this link, enter "Base on your annual bill amount: $[input any value]" and observe that the output values are not calculated correctly. I am feeling frustrated and need assistance on how to generate proper output values. Here is an excerpt from my code:

function unit_val(){
var arr = document.getElementsByName('unit_val');
var unit_val_tot=0;
for(var i=0;i<arr.length;i++){
    if(parseInt(arr[i].value))
        unit_val_tot += parseInt(arr[i].value);
        unit_val_tots =unit_val_tot.toFixed(2);
}
document.getElementById('total_amount').value = unit_val_tots;
document.getElementById('total_amount2').value = unit_val_tots;
}

Alternatively, you can also check the source code of the view page.

Answer №1

Here is a helpful tip for you:

function calculateTotal(){
    var elements = document.getElementsByName('unit_val');
    var totalAmount = 0;
    for(var i=0;i<elements.length;i++){
        if(parseFloat(elements[i].value))
            totalAmount += parseFloat(elements[i].value);
            totalAmountFormatted = totalAmount.toFixed(2);
    }
    document.getElementById('total_amount').value = totalAmountFormatted;
    document.getElementById('total_amount2').value = totalAmountFormatted;
}

Answer №2

After reviewing the data, it appears that the final sum is inaccurate due to a parsing error. The presence of decimals in your values is causing this discrepancy, as using parseInt converts them into whole numbers which may lead to slight discrepancies.

function calculateTotal(){
var elements = document.getElementsByName('unit_val');
var totalAmount = 0;
for(var i=0; i<elements.length; i++){
    if(parseInt(elements[i].value))
        totalAmount += elements[i].value;
        totalAmountFormatted = totalAmount.toFixed(2);
}
document.getElementById('final_total').value = totalAmountFormatted;
document.getElementById('final_total2').value = totalAmountFormatted;
}

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

What could be causing my component to fail to load properly with Vite?

I have been working on a React project using Vite. Following a tutorial I discovered in an article at https://www.digitalocean.com/community/tutorials/how-to-set-up-a-react-project-with-vite, I encountered an issue. Despite following the tutorial step by ...

"Is there a way to retain the value of a variable outside of an ajax success

I've been working on some form validation functions and here's what I've come up with: <script> $(document).ready(function() { var dataObject = {}; $('#username').keyup(function () { id = $(this).attr('id'); ...

The AngularJS Navbar is Bootstrapped

I'm currently working on a project where I need to make a bootstrap navbar show and hide html elements based on data retrieved from an angular controller. Below is the jade code snippet: div.navbar.navbar-fixed-top div.navbar-inner div.c ...

Interacting with PHP through JavaScript function calls

I am facing some frustration with my website due to an issue involving PHP. When I retrieve data from a PHP file, it returns a JSON list like this: {"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurst ...

What are the best practices for managing large amounts of data using jQuery and PHP with AJAX?

When I attempt to pass a large JavaScript array to PHP using the $.ajax method of jQuery, with Content-Type set as JSON and data sent as RAW, I encounter an issue. In PHP, I retrieve the data using file_get_contents('php://input'). Despite every ...

JavaScript's menu button has a callback function assigned to it

The definition can be found below. var CMenu = cc.Sprite.extend({ onClickCallback: null, onClick: function (callback) { this.onClickCallback = callback; }, handleTouches: function (touch, evt) { (this.hovered && this.onClickCallback) &am ...

the order of initialization in angularjs directives with templateUrl

In my current scenario, I am faced with a situation where I need to broadcast an event from one controller and have another directive's controller receive the message. The problem arises because the event is sent immediately upon startup of the contro ...

"Jest test.each is throwing errors due to improper data types

Currently, I am utilizing Jest#test.each to execute some unit tests. Below is the code snippet: const invalidTestCases = [ [null, TypeError], [undefined, TypeError], [false, TypeError], [true, TypeError], ]; describe('normalizeNames', ...

Unable to retrieve the parent element using jQuery

I am facing an issue with my html structure that is generated dynamically through a foreach loop. I have attempted to remove the entire <a> element by accessing it from its ACTIVE HYPERLINK. However, all my efforts seem to be in vain as I am unable t ...

Using a static value in the comparator is necessary for Array.find to function properly in Typescript

Looking to retrieve an item from an array: const device = this.selectedDevtype.devices.find(item => console.log(this.deviceID); return item.device_id === this.deviceID; }); console.log(device); When this.deviceID is logged, it shows "4", but t ...

Do not fulfill the promise until all the images have finished loading

Below is the intended process: Iterate through a collection of img tags Retrieve each tag's src URL Convert it to a base64 encoded string using an HTML 5 canvas Once all images have been converted, resolve the promise and call the callback function ...

Is there a way to stop myself from accidentally clicking twice on the same tile?

I'm currently working on a game and facing an issue where my "X" gets deleted when clicking twice on the same tile. I am able to move my "X" around, but the double-click deletion is causing trouble. I attempted using booleans but struggle with them. I ...

Activate and deactivate form fields on Safari

I have been working on a script to enable and disable a field using Javascript. It functions correctly in Internet Explorer, but I am encountering issues with Safari. FIELD If "Yes" is selected, the free text field below should be enabled; otherwise, it s ...

React Native: Troubleshooting Issue with Shallow Copying of Nested JSON Objects

I have a JSON structure with nested objects like this: {"name", "children": [JSON objects]}. I am attempting to add a new child to the object based on a variable path, which is an array of names. Strangely, my code works fine in the Ch ...

In React, when utilizing the grid system, is there a way to easily align items to the center within a 5 by

I need to center align items within the material-UI grid, with the alignment depending on the number of items. For instance, if there are 5 items, 3 items should be aligned side by side in the center and the remaining 2 items should also be centered. Pleas ...

Empty req.body in Express JS is not fulfilling the necessary data requirements

I've been racking my brain for hours trying to figure out why req.body is showing up empty. I've scoured every corner of stackoverflow and tried every solution that I could find, but nothing seems to be working. Express.js POST req.body empty ...

What advantages can I expect for my client-rendered pages with Gatsby's Client Side Routing?

For a small site I developed, I utilized Gatsby for static content. However, for certain dynamically rendered content, I opted to employ client-only routes in Gatsby. Although I implemented a Header, Footer, and a specific font on my static site, these sa ...

Error encountered when attempting to retrieve JSON data in JavaScript due to being undefined

A snippet of code that reads and writes JSON data is presented below: var info; $(function () { $.getJSON("data.json", function (d) { info = d; }); $('.btn').click(function () { info['c-type'] = $('#c- ...

Determine whether a response is not received within 8 seconds

One of the methods in my Angular component is responsible for returning data Here is a snippet of that method getRecognitionById() { this.loaderService.show(null, true); forkJoin( this.vendorWebApiService.getRecognitionById(this.executiveCh ...

Increasing the upward motion of the matrix raining HTML canvas animation

Recently, I've been experimenting with the Matrix raining canvas animation here and I was intrigued by the idea of making it rain upwards instead of downwards. However, my attempts to achieve this using the rotate() method resulted in skewing and stre ...