Round number to two decimals - javascript

I'm trying to use Math.round for the total to show only two decimals, but it doesn't work as intended. What am I doing wrong?
$(document).ready(function() {
var totalPrice = 0;
$('.food').click(function() {
var $frm = $(this).parent();
var toAdd = $frm.children(".productInput").val();
var addPrice = parseFloat($frm.children(".priceInput").val());
var addAmount = parseFloat($frm.children(".amountInput").val());
if ($('.priceInput').val() == '') {
alert('Price can not be left blank');
};
if ($('.amountInput').val() == '') {
alert('Amount can not be left blank');
} else {
var div = $("<div>");
div.append("<p class='amount'>" + addAmount + "</p>", "<p class='product'> " + toAdd + " </p>", "<p class='price'>" + addPrice + "</p>", "<p class='delete'>" + "X" + "</p>");
$frm.parent().children(".messages").append(div);
totalPrice += addAmount * addPrice;
$(".totalPrice").text("Total Price: $" + totalPrice);
}
console.log(addAmount);
console.log(addPrice);
});
$(document).on("click", ".delete", function() {
/* var subAmount = parseFloat($(this).siblings(".amount").text());
var subPrice = parseFloat($(this).siblings(".price").text());
totalPrice -= subAmount * subPrice;
$(".totalPrice").text("Total Price: $" + totalPrice);*/
$(this).closest("div").remove();
console.log(subPrice);
console.log(subAmount);
});
$(document).on("mouseover", ".delete", function() {
var hoverAmount = parseFloat($(this).siblings(".amount").text());
var hoverPrice = parseFloat($(this).siblings(".price").text());
totalPrice -= hoverAmount * hoverPrice;
Math.round(totalPrice * 100) / 100
$(".totalPrice").text("Total Price: $" + totalPrice);
$(this).closest("div").fadeTo("fast", 0.4);
});
$(document).on("mouseout", ".delete", function() {
var subAmount = parseFloat($(this).siblings(".amount").text());
var subPrice = parseFloat($(this).siblings(".price").text());
totalPrice += subAmount * subPrice;
Math.round(totalPrice * 100) / 100
$(".totalPrice").text("Total Price: $" + totalPrice);
$(this).closest("div").fadeTo("fast", 1.0);
})
});
Since I'm using float, the numbers sometimes get changed into long decimals instead of the exact amount. I'm trying to prevent this by using Math.round. If anyone have another solution to the problem that would be appreciated too.

Use Number.prototype.toFixed() with 2 as argument, in order to round it to two decimals.
Just, remember that the returned value is a String:
let totalPrice = 4.655555;
totalPrice = totalPrice.toFixed(2);
console.log(totalPrice); // "4.66"
console.log(typeof totalPrice); // string
If you want to return a number, use Number(totalPrice.toFixed(2)) — just keep in mind that i.e: Number((7.005).toFixed(2)) will return 7 (without the decimal part)

If you work with currency it is better to use fixed point numbers for precision. There is no fixed-point number type in javascript, so consider using external libraries.
E.g. Big.js or bignumber.js

Related

Filter specific properties and sum the values

I have a Leaflet map with polygons, you can click on each polygon to select them and there is an info window "L.control" that shows the values for the selected polygon. As you continue click on polygons the info window add values for each selected and you get total values for all selected polygons. All this is fine but I need to get down to more detailed sum for specific properties like the example below of regions. If ten polygons are selected I want to differentiate the total amount for regions with properties "REGION SOUTH" and "REGION NORTH" as well as the total of all.
This is the code I'm using, to sum the totals of different properties is no problem but how do you sum for defined properties?
How and where can I add a kind of filter solution that sum only the properties I want?
$.each(statesData.features, function(index, feature) {
var name = `${feature.properties.ZIPCODE} ${feature.properties.Name} ( ${feature.properties.average_time} - ${feature.properties.CITY})`
placenames.push(name);
zipcodes[name] = feature.properties.ZIPCODE;
time = feature.properties.average_time
});
etc....
// Now get the totals of selected polygons
var detailshow = function() {
var result = ''
var total = 0
var total1 = 0
var total2 = 0
var total3 = 0
var total4 = 0
for (var i = 0; i < featuresSelected.length; i++) {
var properties = featuresSelected[i].feature.properties
result +=
`
${properties.CITY}<br>
Zipcode: ${properties.ZIPCODE}
<a href="#" onclick=dellayer(${properties.ZIPCODE})>Delete</a>
<hr>`;
total += properties.amount, // sum amount for all regions
total1 += properties.average_time, // in seconds
total2 += properties.distance,
total3 += properties.amount, // amount for Region South only
total4 += properties.amount, // amount for Region North only
// Convert seconds to timeformat
var convertTime = function (input, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
return [
pad(Math.floor(input / 3600)),
pad(Math.floor(input % 3600 / 60)),
pad(Math.floor(input % 60)),
].join(typeof separator !== 'undefined' ? separator : ':' );
}
var resultTime = convertTime(total1);
}
return {
result: result,
total: total,
resultTime: resultTime,
total2: total2
total3: total3
total4: total4
};
}
detailsselected.update = function(arrayselected) {
var details = detailshow()
this._div.innerHTML =
'<b>Zipcodes</b><br>' +
'Total time: <b>' + details.resultTime + ' hh:mm:ss</b><br>' +
'Total amount: <b>' + details.total + ' st</b><br>' +
'Region South amount: <b>' + details.total3 + ' st</b><br>' +
'Region North amount: <b>' + details.total4 + ' st</b><br>' +
'Distance: <b>' + details.total2.toFixed(1) + ' km</b><br>';
$('#suma', window.parent.document).val(details.resultTime, details.total, details.total2, details.total3, details.total4);
};
detailsselected.addTo(map);
FeatureSelected:
function checkExistsLayers(feature) {
var result = false
for (var i = 0; i < featuresSelected.length; i++) {
if (featuresSelected[i].ZIPCODE == feature.properties.ZIPCODE) {
result = true;
break;
}
};
return result
}
This is part of the json file structure:
var statesData = new L.LayerGroup;
var statesData = {"type":"FeatureCollection","features":[{"type":"Feature","properties":{"ZIPCODE":12345,"CITY":"LONDON","REGION":"REGION SOUTH","amount":1088,"average_time":26150,"distance":2.2},"geometry":{"type":"MultiPolygon","coordinates":...
I did try the following but that did not work...
function filt_north (feature){
if (feature.properties.REGION === 'REGION NORTH' )
return true;
}
total4 += filt_north.(properties.amount), // amount for Region North only
The filt_north function you wrote looks good, just add a filt_south filter to get the south region and do:
let filteredResults = featuresSelected.filter(
result => filt_north(result.feature) || filt_south(result.feature)
);
for (let result of filteredResults) {
var properties = result.feature.properties;
...
Tried your solution, seems it breaks the code and totals is not added up at all = stopped working. I did this, should it be done in a different way?
Filter function:
function filt_south (feature){
if (feature.properties.REGION === 'REGION SOUTH')
return true;
}
function filt_north (feature){
if (feature.properties.REGION === 'REGION NORTH')
return true;
}
Then changed to this (I must be doing something wrong here):
// Now get the totals of selected polygons
var detailshow = function() {
var result = ''
var total = 0
var total1 = 0
var total2 = 0
var total3 = 0
var total4 = 0
let filteredResults = featuresSelected.filter(
result => filt_south(result.feature) || filt_north(result.feature)
);
for (let result of filteredResults) {
var properties = result.feature.properties;
for (var i = 0; i < featuresSelected.length; i++) {
var properties = featuresSelected[i].feature.properties
result +=
`
${properties.CITY}<br>
Zipcode: ${properties.ZIPCODE}
<a href="#" onclick=dellayer(${properties.ZIPCODE})>Delete</a>
<hr>`;
total += properties.amount, // sum amount for all regions
total1 += properties.average_time,
total2 += properties.distance,
total3 += filt_south (properties.amount), // amount for Region South only
total4 += filt_north (properties.amount) // amount for Region North only
// Convert seconds to timeformat
var convertTime = function (input, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
return [
pad(Math.floor(input / 3600)),
pad(Math.floor(input % 3600 / 60)),
pad(Math.floor(input % 60)),
].join(typeof separator !== 'undefined' ? separator : ':' );
}
var resultTime = convertTime(total1);
}
}
return {
result: result,
total: total,
resultTime: resultTime,
total2: total2
total3: total3
total4: total4
};
}
detailsselected.update = function(arrayselected) {
var details = detailshow()
this._div.innerHTML =
'<b>Zipcodes</b><br>' +
'Total time: <b>' + details.resultTime + ' hh:mm:ss</b><br>' +
'Total amount: <b>' + details.total + ' st</b><br>' +
'Region South amount: <b>' + details.total3 + ' st</b><br>' +
'Region North amount: <b>' + details.total4 + ' st</b><br>' +
'Distance: <b>' + details.total2.toFixed(1) + ' km</b><br>';
$('#suma', window.parent.document).val(details.resultTime, details.total, details.total2, details.total3, details.total4);
};
detailsselected.addTo(map)

Javascript Donation Calculator - Issue with calculation

I am having a bit of an issue with my JavaScript Donation Calculator, It works well, however when I am calculating the percentage of 50, it comes up as $12.5 and I would like it to be $12.50, this also effects $7.50 it shows up at 7.5.
I have included the code below
// set the variables
var donationSubmit = document.getElementById('donationSubmit');
// turn the outputs into variables as I am sure they will be used more than once per page load
var afterCreditOutput = document.getElementById('afterCreditOutput')
var totalCostOutput = document.getElementById('totalCostOutput');
/* jquery stuffs */
$maxDonation = 1200
// calculate the value on keyup
$inputValue = $('input[name="donation_amount"]');
$('#customDonationAmount').keyup(function(){
if ($inputValue.val() > $maxDonation) {
$inputValue.val($maxDonation);
}
if ($inputValue.val() === "") {
afterCreditOutput.innerHTML = ("Please enter a value or choose from one of the preset values above");
totalCostOutput.innerHTML = ("");
}
calculateCustomTaxCredit();
});
// calculate the value on enter
/*
$inputValue.bind('keypress', function(e) {
if(e.which == 13) {
calculateCustomTaxCredit();
}
});
*/
/* end of jquery */
// validate the keystrokes and ensure the only things pressed are numbers
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
// super ugly and hacky but it does the job.
document.getElementById('donationAmount-20').onclick = applyButtonAmount;
document.getElementById('donationAmount-50').onclick = applyButtonAmount1;
document.getElementById('donationAmount-100').onclick = applyButtonAmount2;
document.getElementById('donationAmount-400').onclick = applyButtonAmount3;
document.getElementById('donationAmount-1200').onclick = applyButtonAmount4;
function applyButtonAmount() {
document.forms["donation-form"]["donation_amount"].value = (20);
calculateCustomTaxCredit()
}
function applyButtonAmount1() {
document.forms["donation-form"]["donation_amount"].value = (50);
calculateCustomTaxCredit()
}
function applyButtonAmount2() {
document.forms["donation-form"]["donation_amount"].value = (100);
calculateCustomTaxCredit()
}
function applyButtonAmount3() {
document.forms["donation-form"]["donation_amount"].value = (400);
calculateCustomTaxCredit()
}
function applyButtonAmount4() {
document.forms["donation-form"]["donation_amount"].value = (1200);
calculateCustomTaxCredit()
}
/* Where all the magic happens */
// Helper Funcs
// oh JavaScript why are you so bad at rounding.
function round(number, precision) {
var shift = function (number, precision, reverseShift) {
if (reverseShift) {
precision = -precision;
}
numArray = number.toString().split("e");
return +(numArray[0] + "e" + (numArray[1] ? (+numArray[1] + precision) : precision));
};
// number = shift(number, precision, false);
// number = Math.round(number);
// number = shift(number, precision, true);
return shift(Math.round(shift(number, precision, false)), precision, true);
}
// return a percentage
function per(num, amount){
return num*amount/100;
}
// calculate
function calculateCustomTaxCredit() {
var donationAmount = document.forms["donation-form"] ["donation_amount"].value;
// if there is nothing in the input then fail
if (donationAmount === "") {
afterCreditOutput.innerHTML = ("Please enter a value or choose a preset value");
// check has passed - this is a number
}else {
if(donationAmount <= 100 ) {
console.log("Initial amount: " + donationAmount);
var costAfterCredit = per(donationAmount, 25);
var credit = per(donationAmount, 75);
var cleanCostAfterCredit = round(costAfterCredit, 2)
var cleanCredit = round(credit, 2);
console.log(donationAmount);
if(donationAmount == '50') {
alert('hi');
}
afterCreditOutput.innerHTML = ("Cost after Tax Credit:" + " <span
class='green'>$" + cleanCostAfterCredit + "</span>");
totalCostOutput.innerHTML = ("Total Amount:" + " <span class='green'>$" +
donationAmount + "</span>");
//TESTING CODE
console.log('75% tax credit');
console.log('Money saved: ' + credit);
console.log('Money spent: ' + costAfterCredit);
console.log('Money saved: ' + cleanCredit + " CLEAN");
console.log('Money spent: ' + cleanCostAfterCredit + " CLEAN");
}else if(donationAmount > 100 && donationAmount <= 550) {
console.log("Initial amount: " + donationAmount);
var costAfterCredit = per(donationAmount, 50);
var credit = per(donationAmount, 50);
var cleanCostAfterCredit = round(costAfterCredit, 2)
var cleanCredit = round(credit, 2);
afterCreditOutput.innerHTML = ("Cost after Tax Credit: Approx" + " <span class='green'>$" + cleanCostAfterCredit + "</span>");
totalCostOutput.innerHTML = ("Total Amount:" + " <span class='green'>$" + donationAmount + "</span>");
//TESTING CODE
//console.log('75% tax credit');
//console.log('Money saved: ' + credit);
//console.log('Money spent: ' + costAfterCredit);
//console.log('Money saved: ' + cleanCredit + " CLEAN");
//console.log('Money spent: ' + cleanCostAfterCredit + " CLEAN");
}else {
console.log("Initial amount: " + donationAmount);
var costAfterCredit = per(donationAmount, 66.6666666666666);
var credit = per(donationAmount, 33.3333333333333);
var cleanCostAfterCredit = round(costAfterCredit, 2)
var cleanCredit = round(credit, 2);
if(cleanCredit >= 500) {
cleanCostAfterCredit = donationAmount - 500;
}
afterCreditOutput.innerHTML = ("Cost after Tax Credit:" + " <span c class='green'>$" + cleanCostAfterCredit + "</span>");
totalCostOutput.innerHTML = ("Total Amount:" + " <span class='green'>$" + donationAmount + "</span>");
//TESTING CODE
//console.log('75% tax credit');
//console.log('Money saved: ' + credit);
//console.log('Money spent: ' + costAfterCredit);
//console.log('Money saved: ' + cleanCredit + " CLEAN");
//console.log('Money spent: ' + cleanCostAfterCredit + " CLEAN");
}
}
};
Here is also a pastebin with more readable code:
goo.gl/UQZrik
In the end I am trying to have the variable cleanCostAfterCredit set to 12.50 instead of 12.5 when a calculation is done. Also if anyone can give me any tips on making my code more efficient I would really appreciate it. please lay on the constructive criticism :)
Use .toFixed(2) which will return a string representing the 2 decimals.
var result = 12.5;
var resultWithDecimals = result.toFixed(2);
The toFixed method formats floats but is not culture aware.
donationAmount.toFixed(2)
If you want to be culture aware, you should use toLocaleString
console.log(
// This uses the default locale
(12.5).toLocaleString(undefined, {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
})
);
console.log(
(1).toLocaleString('pt-br', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
})
);

Breaking down a JavaScript code into functions

Newbie student coder,
Here and I am developing a program that can alert program that once you type in the amount of money you give it will calculate the tip, and tax to get the total amount that the user owns. I have the base code down and divided it up into functions but when I put in a number it shows as unidentified.
Here is my code:
const TAXRATE=.095
const TIPRATE=.2
function foodCharge (foodCharge) {
return parseFloat(prompt("please enter the amount"));
}
foodCharge ();
function taxAmount (foodCharge,TAXRATE) {
return parseFloat(foodCharge*TAXRATE);
}
taxAmount();
function subAmount (foodCharge,taxAmount) {
return parseFloat(foodCharge+taxAmount);
}
subAmount ();
function tipAmount (TAXRATE,subAmount) {
return parseFloat (TAXRATE*subAmount);
}
tipAmount ();
function grandTotal (foodCharge, taxAmount, tipAmount) {
return grandTotal=parseFloat(foodCharge+taxAmount+tipAmount)
}
grandTotal ();
function finalCost(foodCharge,taxAmount, tipAmount, grandTotal ) {
alert ("Meal cost: "+ foodCharge + " \nTax: " + taxAmount + " \nTip: " +
tipAmount +" \nGrand total: " + grandTotal);
}
finalCost();
You need parseFloat function only when you parse float number from string. You don't need to parse result of regular math operation(if both numbers are not strings). When you pass function as a parameter to alert() you must pas it with brackets (), otherwise you pass the reference to a function.
If i correctly understand your question, here is your program:
const TAXRATE=0.095
const TIPRATE=0.2
function foodCharge (foodCharge) {
return parseFloat(prompt("please enter the amount"));
}
var charge = foodCharge ();
function taxAmount (charge, rate) {
return charge*rate;
}
var tax = taxAmount(charge, TAXRATE);
function subAmount (charge,tax) {
return charge+tax;
}
var amount = subAmount (charge,tax);
function tipAmount (rate,amount) {
return rate*amount;
}
var tip = tipAmount(TAXRATE,amount);
function grandTotal () {
return charge+tax+tip;
}
function finalCost() {
alert ("Meal cost: "+ charge + " \nTax: " + tax + " \nTip: " + amount +" \nGrand total: " + grandTotal());
}
finalCost();
You can adjust the function to be called within finalCost. Note, parseFloat() is only necessary at foodCharge function
const TAXRATE = .095
const TIPRATE = .2
function foodCharge() {
return parseFloat(prompt("please enter the amount"));
}
function taxAmount(charge, tax) {
return charge * tax;
}
function subAmount(charge, tax) {
return charge + tax;
}
function tipAmount(tip, sub) {
return tip * sub;
}
function grandTotal(charge, tax, tip) {
return charge + tax + tip;
}
function finalCost() {
let _foodCharge = foodCharge();
let _taxAmount = taxAmount(_foodCharge, TAXRATE);
let _subAmount = subAmount(_foodCharge, _taxAmount);
let _tipAmount = tipAmount(TIPRATE, _subAmount);
let _grandTotal = grandTotal(_foodCharge, _taxAmount, _tipAmount);
alert("Meal cost: " + _foodCharge + " \nTax: " + _taxAmount + " \nTip: " +
_tipAmount + " \nGrand total: " + _grandTotal);
}
finalCost();

javascript passing functions nan and undefined errors

This works tell I hit the tax function. Then I start getting
nan and undefined errors. Cant figure out why the tax function is not picking up the code from the other functions.
/ Saturday May 27 2017
{
// Global variables
var orderCount = 0;
var takeOrder = function (topping, crustType) {
// add one to order count
orderCount = orderCount + 1
return('Order: ' + crustType + ' pizza topped with ' + topping );
}
var getSubTotal = function(itemCount){
var subTatal = (itemCount * 7.5);
return (subTatal + ' subtotal of ' + ' itemCount ' + (itemCount));
}
var getTax = function (){
var subTatal = subTatal * 0.06;
// getTheTax = (subTatal * 0.06)
return subTatal + ' with tax of ' + (subTatal)
}
var getTotal = function (){
var myTotal = getSubTotal + getTax;
return ' tax ' + getTax + 'plus subtotal ' + getSubTotal() + ' is ' + (myTotal);
}
console.log(takeOrder('bacon', 'thin crust'));
console.log(takeOrder('cheese', 'thick crust'));
console.log(takeOrder('pepperoni', 'medium crust'));
console.log(getSubTotal(10));
console.log(' getTax ' + getTax());
console.log(getTotal());
}
This is the corrected version of your code.
var takeOrder = function(topping, crustType) {
console.log('Order: ' + crustType + ' pizza topped with ' + topping);
return 1;
}
var getSubTotal = function(orderCount) {
var subTotal = (orderCount * 7.5);
console.log('Subtotal of ' + subTotal.toFixed(2) + ' with item count ' + orderCount);
return subTotal;
}
var getTax = function(subTotal) {
var tax = subTotal * 0.06;
console.log('Tax is ' + tax.toFixed(2));
return tax;
}
var getTotal = function(subTotal, tax) {
var total = subTotal + tax;
console.log('Total is ' + total.toFixed(2));
return total;
}
var orderCount = 0;
orderCount += takeOrder(orderCount, 'bacon', 'thin crust');
orderCount += takeOrder('cheese', 'thick crust');
orderCount += takeOrder('pepperoni', 'medium crust');
var subTotal = getSubTotal(orderCount);
var tax = getTax(subTotal);
var total = getTotal(subTotal, tax);
Summary of corrections
Made functions return Number rather than String
Now all functions are almost pure functions (don't cause side-effects other than logging)
Formatted numbers prior to printing them by rounding them to the second decimal
Fixed typographic errors (tatal rather than total).
Added parenthesis to function invocations (e.g: getTax() rather than getTax
Removed redundant invocations
More
you are defining a variable, and assigning into it it's value times something.
var subTatal = subTatal * 0.06;
In this case, subTatal does not have a value.
I think you should read about variables and scopes.
Read the link below:
https://www.w3schools.com/js/js_scope.asp
Your both function is returning the string :
....
return subTatal + ' with tax of ' + (subTatal)
...
return ' tax ' + getTax + 'plus subtotal ' + getSubTotal() + ' is ' + (myTotal);
You can go through this blog for converting strings to number:
https://coderwall.com/p/5tlhmw/converting-strings-to-number-in-javascript-pitfalls
Please make sure the what is the type of value you want to be returned form the function to use it.
var subTatal = subTatal * 0.06;
is equivalent of
var subTatal = undefined;
subTatal = subTatal * 0.06;
note, this subTatal is not the same as the one defined outside the function (learn scope)
If you create a variable inside a function it will exists only inside that function, so if you call that variable from inside another it will be undefined.
There are two ways:
declare these variables as global at the top of your code just like orderCount
functions can have inputs and output, so you can pass to a function the variable you need and ask it to return the result, which can be saved into a variable and later used.
For example:
function getSubtotal(orderCount) {
var subtotal = //do something
return subtotal }
function getTax(subtotal) {
var tax = //calculate tax
return tax }
var subtotal = getSubtotal(orderCount)
var tax = getTax(subtotal)

Update total variable when quantity is changed

I'm having trouble updating the total when I change the "Complete E-Book" product quantity. When I first set the quantity and add it to basket it shows the correct total within the basket but when I change the quantity it adds on to the previous total. Overall I want to be able to add multiple products to the basket total (reason for x += p2Total (x var is what holds the total - Line 86) but while allowing for the Quantity of the product to be changed and then updated in the total.
Codepen Here >
Products in question are the top 2
JS:
// JQuery Functions for NavBar - Class Toggle
(function() {
$('.hamburger-menu').on('click', function() {
$('.bar').toggleClass('animate');
})
})();
(function() {
$('.hamburger-menu').on('click', function() {
$('.bar2').toggleClass('ApprDown');
})
})();
/*
START OF BASKET
START OF BASKET
*/
// Get access to add to basket basket button
var addToBasket = document.querySelector('.atbb');
addToBasket.addEventListener('click', P1);
// Formatter simply formats the output into a currceny format istead of a general number format. This is using the ECMAScript Internationalization API
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'GBP',
minimumFractionDigits: 2,
});
var totalBasket
var discountLimit = 10
var discount = 3.50
var x = 0.00
// One big function with different condtions based on the differnt products and then simply concatinate the values where needed
function P1() {
var y = document.getElementById("p1Quant").value;
if (+y > discountLimit) {
var z = 15.000
x = parseFloat(+y) * parseFloat(+z); // + will convert the vars into Numbers etc
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(x) + ("<br/>") + ("<hr />") + ("<div class='strike'>Plus £3.50 Delivery</div>") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(x)
// Jquery Notificaiton
var truckVar = document.getElementById("truck");
truckVar.setAttribute("class", "animateTruck");
} else if (+y <= 0) {
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(0) + ("<br/>") + ("Total: ") + formatter.format(0)
} else {
var z = 15.000
var s = 15.000
x = parseFloat(+y) * parseFloat(+z) + 3.50
var sub = parseFloat(+y) * parseFloat(+s)
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(sub) + ("<br/>") + ("<hr />") + ("Plus £3.50 Delivery") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(x)
}
}
var addToBasket2 = document.querySelector('.atbb2');
addToBasket2.addEventListener('click', P2);
function P2() {
p2Total = 0.00
var y = document.getElementById("p2Quant").value;
var p2 = 8.00
var p2Total = parseFloat(+y) * parseFloat(+p2); // + will convert the vars into Numbers etc
// var totalBasket = + x + x // javascript add value onto set var
x += p2Total // Append the amount to the basket
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(x) + ("<br/>") + ("<hr />") + ("<div class='strike'>Plus £3.50 Delivery</div>") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(x)
if (+y <= 0) {
p2Total = 0.00
}
}
Don't add the value to x, add x and p2Total into a new temporary value that is scoped to the function itself and use that.
var tmp_total = x + p2Total;
document.getElementById("BasketSumData").innerHTML = ("Sub Total: ") + formatter.format(tmp_total) + ("<br/>") + ("<hr />") + ("<div class='strike'>Plus £3.50 Delivery</div>") + ("<br/>") + ("<hr />") + ("Total: ") + formatter.format(tmp_total)

Categories

Resources