Can anyone have a look and see why JS i concatenating values instead of adding them? https://codepen.io/mateusz-baran/pen/XWpGdvj
$(document).ready( function () {
// VARIABLES
// ----------------------------------------------------------
var amount, percent, result;
var calculator = $('.calculator');
var simAmount = calculator.find('.calculator__numsims');
var pricePerUse = calculator.find('.calculator__peruse');
var daysOpen = calculator.find('.calculator__daysopen');
var occupancy = calculator.find('.calculator__occupancy');
var monthlyRev = calculator.find('.calculator__monthlyrev');
var yearlyRev = calculator.find('.calculator__yearlyrev');
var roiEta = calculator.find('.calculator__roieta');
var calculatorResult = calculator.find('.calculator__result');
var txtPerUse = calculator.find('.peruse');
var txtSimNum = calculator.find('.simnum');
var txtDaysOpen = calculator.find('.daysopen');
var txtOccupancy = calculator.find('.occupancy');
var txtMonthlyRev = calculator.find('.calculator__monthlyrev');
var txtYearlyRev = calculator.find('.calculator__yearlyrev');
var txtRoiETA = calculator.find('.calculator__roieta');
// INIT BILL
// ----------------------------------------------------------
$(window).on('DOMContentLoaded', function () {
calcAmount();
});
// RANGE FUNCTION
// ----------------------------------------------------------
calculator.on('input', function () {
calcAmount();
});
function calcAmount()
{
txtDaysOpen.text(daysOpen.val());
txtOccupancy.text(occupancy.val());
txtSimNum.text(simAmount.val());
txtPerUse.text(pricePerUse.val());
calculatorResult.text(addCommas(((simAmount.val() + occupancy.val()))));
txtMonthlyRev.text(addCommas((((((occupancy.val() / 100) * pricePerUse.val()) * simAmount.val() ) ) * daysOpen.val()) * 4));
txtYearlyRev.text(addCommas(((((((occupancy.val() / 100) * pricePerUse.val()) * simAmount.val() )) * daysOpen.val()) * 4) * 12));
txtRoiETA.text(parseInt((calculatorResult.text().replace(',','') / txtMonthlyRev.text().replace(',','')) + " months"));
};
function addCommas(nStr) {
var tst = Math.round(nStr);
var num = (tst + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
this is line 55 in JS section.
With the default data loaded - I would expect to see result as: 110,000 but iam getting 10,000,010,000 - so the numbers are getting concatenated and not added
Can anyone help?
+concatenates when one of the values is a string. Try converting the input values to numbers first?parseInt()for parsing strings that contain valid integers. Note thatparseInt()may returnNaNif it has not able to parse the integer inside the string.