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>