JavaScript's addition function is not functioning properly

Does anyone know how to calculate the sum of these variables?

var totalPrice = document.values.T1.value;

var pounds = document.values.T2.value;

var serviceFee = 5.00

var counter1 = 0;

var counter2 = 0;

var processing = 0;

var shippingCost = 0;

var tax = 0;

var GrandTotal = totalPrice + serviceFee + shippingCost + processing + tax;

Appreciate any help.

Answer №1

The value of elements is always represented as a string, so using the + operator will result in concatenation, not addition.

To perform mathematical operations, convert string values to numbers:

var price = +document.values.T1.value;
var pounds = +document.values.T2.value;

In this example, I've used the unary plus + operator, which considers the entire string. Alternatively, you can use parseFloat, which ignores any invalid characters at the end of the string; the choice depends on your specific requirements for handling input data.

Here's a demonstration:

var price = "5";   // Simulating document.values.T1.value
var pounds = "10";     // Simulating document.values.T2.value
var serviceCharge = 5.00
var counter1 = 0;
var counter2 = 0;
var processingFee = 0;
var shippingCost = 0;
var tax = 0;
var total = price + serviceCharge + shippingCost + processingFee + tax;

snippet.log(total); // "55000" - incorrect

// Instead:
price = +"5";    // Simulating document.values.T1.value 
pounds = +"10";      // Simulating document.values.T2.value
total = price + serviceCharge + shippingCost + processingFee + tax;

snippet.log(total); // "10" - correct
<!-- The script provides the `snippet` object, refer to http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

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

Creating a unique navigation route in React

My application has a consistent layout for all routes except one, which will be completely different from the rest. The entire application will include a menu, body, footer, etc. However, the one-off route should be standalone without these elements. How ...

Tips for updating the DOM within a map function by utilizing the onChange event with a checkbox and react hooks

Initially, I imported a basic "database" object from another file that contains an array of students. I then used map to iterate through the student array and display all the students on the window object. Everything was working fine until I attempted to ...

What is the best way to test speedy AJAX response times using Webdriver.io?

Currently, I am creating Cucumber.js tests using Webdriver.io. Everything seems to be going smoothly, but I'm encountering an issue with the mock server responding too quickly with AJAX. The "Loading..." message is not visible because the content load ...

Encountered an issue while attempting npm install, with the error message "Error: Undefined variable standalone_static_library in binding.gyp" and node-sass chokidar error

I've been working on updating a Ruby on Rails and React project from 3 years ago. However, I encountered an issue while trying to npm install. $ npm install gyp: Undefined variable standalone_static_library in binding.gyp while trying to load binding ...

Attempting to run the npm install command led to encountering a SyntaxError with an

Recently, I made some alterations to my npm configuration and ever since then, I have been consistently encountering the same error whenever I try to install various packages. It seems that due to a personal mistake in changing the npm settings, I am now u ...

Deleting information from several stores in React Reflux using a single action function

In the AuthActions file, there is a straightforward function called _clear that assigns this.data to undefined. This function is only invoked when a user logs out. However, upon logging back in with a different user, remnants of data from the previous ac ...

Passing JSON information through PatternLab

Incorporating an atomic pattern and passing data from a JSON array is my goal. Below are the code snippets and JSON file. anchor-link.mustache <a href="{{ url }}" class="{{ class }}">{{ label }}</a> footer-nav.mustache <ul class="menu ve ...

KnockoutJS is unable to assign a negative value to an input field

Is there a way to assign the value of an <input> as false? It seems to work fine with true. Data Model: function DataModel(){ self = this; self.Flag = ko.observable(false); }; HTML Code: <input type="text" data-bind="value:Flag"/> ...

Issue with displaying value after rendering

After fetching pool data from the constants file, my task was to create a featured vault - the one with the highest APY Reward value obtained from the API. Even though I successfully fetched all three values and performed the calculations, I am facing an i ...

Redux: utilizing yield within an unrecognized function

Hey there! I am brand new to Reudx-Saga and have been experimenting with it for the past few days. I feel pretty comfortable with generators, actions, redux-stores, sagas, and other concepts. Overall, I have a good amount of experience with JavaScript. C ...

The node.js express framework is unable to fetch the URL and data from the node server

Attempting to create a basic application to retrieve data from a nodejs server. But encountering issues with accessing the file in both the browser and POSTMAN. Despite multiple attempts to verify the URLs, I have been unsuccessful. Below are the files i ...

Unable to identify the pdf file using multer in node.js

const multer=require('multer'); var fileStorage = multer.diskStorage({ destination:(req,file,cb)=>{ if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype==='image/png') { ...

Upcoming 13.4 Error: NEXT_REDIRECT detected in API routes

Here is the code snippet from my /app/api/auth/route.ts file: import { redirect } from 'next/navigation'; export async function GET(req: Request) { try { redirect('/dashboard'); } catch (error) { console.log(error); ...

Design the parent element according to the child elements

I'm currently working on a timeline project and I am facing an issue with combining different border styles for specific event times. The main challenge is to have a solid border for most of the timeline events, except for a few instances that share a ...

Is it possible to maintain component data in Angular while also incorporating dynamic components?

All the code you need can be found here: https://stackblitz.com/edit/angular-keep-alive-component?file=src/app/app.component.ts Is it possible to maintain the state of entered values when switching components? I am currently utilizing dynamic component r ...

Filtering a deeply nested object based on an array of keys in JavaScript

I have received an object and an array. My task is to filter the object so that it only contains nodes where either the key or the value matches with the keys provided in the array. For example: Array containing keys - ['student1', 'STU&apo ...

When using jQuery's ajax() function, it is possible to pass HTML as data and change the ampersands in URLs to &amp;

I have encountered an issue where I am capturing the HTML content of a page and attempting to send it as a string to a PHP web service using jQuery's ajax() function. However, when I receive the parameter on the PHP side, the &s in the URLs present wi ...

JavaScript's Array.map function failing to return a value

Here is a snippet of code from an api endpoint in nextJS that retrieves the corresponding authors for a given array of posts. Each post in the array contains an "authorId" key. The initial approach did not yield the expected results: const users = posts.ma ...

Exploring the life cycle of React.js components, how state behaves within them, and the asynchronous nature

There seems to be an issue with the expected data result and the actual data result. Even though the fetchData() and fetchnumberOfCommits() methods are being called from the componentWillMount(), the array is empty at first. However, the render method is b ...

Clicking on the parent page prevents the hyperlink inside the iframe from working as expected

I am having an issue with a hyperlink inside an iframe. When I click on it in the parent page, it doesn't work. Here is how it is set up: iframe.html <h1>I'm inner page!</h1> <a id="shared" class="btn" href=&q ...