I'm not so good with JS and for some reason when I try to add two fields together it joins them rather than adding the sum together.. this is the code I'm trying to use..
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = postageVal.substr(1); //68.50
var subtotal = subtotalVal.substr(1); //378.00
var totalVal = postage+subtotal;
alert(postage);
alert(subtotal);
alert(totalVal);
};
The totalVal is echoing/alerting out 68.50378.00 rather than adding them together.. could someone please tell me where I've gone wrong? :( The idea is to update the "total" textfield with totalVal, but I haven't gotten that far yet!
1 Answer. This happens when one or both of the variables is String which results in string concatenation. The arithmetic operators like / * - performs a toNumber conversion on the string(s). In order to convert a string to a number : use the unary + operator.
Add numbers in JavaScript by placing a plus sign between them. You can also use the following syntax to perform addition: var x+=y; The "+=" operator tells JavaScript to add the variable on the right side of the operator to the variable on the left.
You need to convert your values to a float before adding them:
var totalVal = parseFloat(postage) + parseFloat(subtotal);
EDIT: Here's a complete example that includes a check for NaN:
function calculateTotal() {
var postageVal = document.getElementById('postage').value; //$68.50
var subtotalVal = document.getElementById('subtotal').value; //$378.00
var postage = parseFloat(postageVal.substr(1)); //68.50
var subtotal = parseFloat(subtotalVal.substr(1)); //378.00
var postageAsFloat = isNaN(postage) ? 0.0 : postage;
var subtotalAsFloat = isNaN(subtotal) ? 0.0 : subtotal;
var totalVal = postageAsFloat + subtotalAsFloat;
alert(postage);
alert(subtotal);
alert(totalVal);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With