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

Attach an event listener to a class, then use the removeEventListener method to detach the listener and eliminate any remaining references, ensuring proper functionality of the

When creating a class in JavaScript, a normal function returns the class object. However, events return the event object and the class object is lost: function class(a){ this.name=a; document.addEventListener('click',this.click,false); xhr.add ...

How can I show a title when redirecting a URL in VUE JS?

My current setup includes a navigation drawer component that changes the title based on the user's route. For example, when navigating to the home page (e.g. "/"), the title updates to "Home", and when navigating to the profile page (e.g. /profile), t ...

Nesting ng-repeat within another ng-repeat for dynamic content generation

I am currently working on a page that requires displaying boxes (using ng-repeat) containing information about channels and their corresponding cities. The issue I am encountering arises when repeating the second ng-repeat: <table class="table table-c ...

Alert: React-Weather is causing an invalid element type in React

I am feeling overwhelmed. I have created a custom component called react-weather which has been installed using npm. Here is the code snippet for my self-written Weather.js component located in the src/components folder: import React, { Component } from & ...

Tips on presenting our data using JSON structure

Hey there! I'm new to Next JS and I'm looking to showcase the data from my index.js file in JSON format in my dynamicid.js file. Can anyone guide me on how to achieve this? index.js In my index.js file, I currently display my output but now I ...

Is there a way to compare data before and after revalidation using useSWR?

With the use of Next.js and through the implementation of useSWR, data is fetched from an endpoint every 30 seconds using an automatic revalidation interval (https://swr.vercel.app/docs/revalidation#revalidate-on-interval). Within the retrieved data, there ...

Passing the unique identifier of a record in NextJS to a function that triggers a modal display

I'm currently facing an issue with my NextJS component that displays a list of people. I have implemented a delete button which triggers a modal to confirm the deletion of a person, but I am struggling with passing the id of the person to be deleted. ...

Using Jquery to display text when the condition is not met

Here is the code snippet I am currently working with: http://jsfiddle.net/spadez/mn77f/6/ I am trying to make it display a message when there are no fields (questions) present. I attempted to achieve this by adding the following lines of code: } else ...

A guide to transferring modules between component files in JavaScript

My query pertains to the handling of imports in web pages. When a file is imported into another, do the declarations and imports from the imported file become available in the file where it is being imported? A suggestion was made for me to import a compo ...

Learn how to organize a div element containing select options using categories such as gender and shoe size, similar to the filtering

Is there a way to sort div elements using a select menu, similar to how it is done on shopping websites? I am struggling with modifying my JS code in order to implement multiple selects. Although I believe my JS code is correct, it doesn't seem to be ...

Identify when a click occurs outside specific elements

I've been searching for solutions to address this issue, but so far nothing has worked. Here is the JavaScript code I am using: var specifiedElement = document.getElementById('a'); document.addEventListener('click', function(eve ...

Steps for resolving the "endless redirection loop" issue in Sharepoint

I am currently learning Javascript and working on setting up a multi-language Sharepoint site. I am trying to implement a code into each page that checks the user's email and the language in the URL (Portuguese or Spanish) and then redirects according ...

Animating with React using the animationDelay style does not produce the desired effect

Is there a way to apply an animation to each letter in a word individually when hovering over the word? I want the animation to affect each letter with an increasing delay, rather than all at once. For example, if scaling each letter by 1.1 is the animatio ...

Utilizing Windows Azure and restify for node.js Development

I have an azure website with a URL like: . In my server.js file, I have the following code: var restify = require('restify'); function respond(req, res, next) { res.send('hello ' + req.params.name); next(); } var server = restify ...

Tips for adding new items to a Masonry Image List using React MUI

As I experiment with utilizing the React MUI Masonry Image List alongside the infinite scroll, I've found that they complement each other quite well. However, a challenge arises when appending new images to the Masonry image list. While I can success ...

The AJAX success callback function failed to execute in cases where the dataType was set to JSONP during Cross domain Access

type = 'math'; var ajurl = "sample.com&callback=myhandler"; var datas = "cateid=" + cateid + "&type=" + type + "&pno=" + pno + "&whos=" + whos; $.ajax({ type: "GET", url: ajurl, data: datas, contentType: "application/json; ...

The html-duration-picker is not being displayed in the proper format

I've been working on integrating an external library that allows for inputting document length. Specifically, I'm using the html-duration-picker library, but it seems like the input functionality is not quite right for durations. Could it be th ...

I have my server running on port 6666. I am able to receive a response from Postman, however, when I attempt to access localhost:6666 in my browser, it displays a message

[image description for first image][1] [image description for second image][2] [image description for third image][3] There are three images displayed, indicating that the server is operational and responding with "hello" in Postman, but there seems to ...

Retrieving Twitter posts using the screen_name parameter in a Node.js environment

I am looking to create a website that allows users to enter the Twitter screen name of any celebrity. When the user clicks on the "show tweet" button, the latest tweet from that screen name will be displayed. I am interested in implementing this feature ...

JQuery Ajax: The loaded content flickers into view, revealing old content momentarily

Having an issue with my ajax code. I am working on a project that involves some links and a content area. The idea is that when a user clicks on a link, the content area should be hidden, load new data, and then show the updated content. However, I have no ...