jQuery calculating two values wrong and not sure why - javascript

Any ideas why the total I'm trying to calculate together is coming out as 1.00?
$(document).ready(function() {
// Hide initial values that need updating
$("#estimated-shipping em, .cart-finalTotal span, .cart-vat span").hide();
// get current delivery rate
$("#get_rate").trigger('click');
// set a timeout and get total and shipping that was generated and add together for nnew total
setTimeout(function() {
// get cart sub-total
var a = $(".cart-total span").html().replace(/[$£]/gi, "");
var ib = $("#estimated-shipping em").html().replace(/[$£]/gi, "");
if (ib == "FREE") {
$("#estimated-shipping em").html("FREE");
var b = "0.00";
} else {
var b = parseFloat($("#estimated-shipping em").text().replace(/\$|£/gi, ""));
}
// add together sub-total and estimated shipping to new total
// update with new total with sub-total and added shipping
var total = parseFloat(a) + parseFloat(b);
total = parseFloat(Math.round(total * 100) / 100).toFixed(2);
$('.cart-finalTotal span').text("£" + total);
// show new values
$("#estimated-shipping em, .cart-finalTotal span, .cart-vat span").show();
}, 2000);
$(".item-quantity input").on("change", function() {
document.location.href = location.href
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="cart-right">
<p class="cart-total">Sub-Total<span class="money">£1,245.00</span>
</p>
<p class="cart-vat">VAT 20% (included)<span class="money" style="display: block;">£249.00</span>
</p>
<p class="cart-delivery">Delivery (estimated)<span class="money" id="estimated-shipping">+ <em style="display: inline;">FREE</em></span>
</p>
<p class="cart-finalTotal">Total<span class="money" style="display: block;">£0.00</span>
</p>
</div>

In your subtotal, you have a comma, parseFloat will stop when it see a non numeric character that isn't a dot. So parse float is returning a 1 not a 1245. You need your regex to be something more on the lines of /[^0-9.]/g.
Here is code that is working:
$(document).ready(function() {
// Hide initial values that need updating
$("#estimated-shipping em, .cart-finalTotal span, .cart-vat span").hide();
// get current delivery rate
$("#get_rate").trigger('click');
// set a timeout and get total and shipping that was generated and add together for nnew total
setTimeout(function() {
// get cart sub-total
var a = $(".cart-total span").html().replace(/[^0-9.]/gi, "");
if ($("#estimated-shipping em").text() == "FREE") {
$("#estimated-shipping em").html("FREE");
var b = "0.00";
} else {
var b = parseFloat($("#estimated-shipping em").text().replace(/[^0-9.]/gi, ""));
}
// add together sub-total and estimated shipping to new total
// update with new total with sub-total and added shipping
var total = parseFloat(a) + parseFloat(b);
total = parseFloat(Math.round(total * 100) / 100).toFixed(2);
$('.cart-finalTotal span').text("£" + total);
// show new values
$("#estimated-shipping em, .cart-finalTotal span, .cart-vat span").show();
}, 2000);
$(".item-quantity input").on("change", function() {
document.location.href = location.href
});
});

Related

Removing the shipping price, if the amount has reached a certain value

So I have a working shopping cart page, but I do not know how to remove the shipping value, once a user has reached a total, for example, of 50 or higher. In the previous version this was already implemented, so I tried to compare and figure out how to implement this in the new page, but am not skilled enough in JavaScript. This is the JavaScript I am using right now.
$(document).ready(function() {
var taxRate = 0.05;
var shippingRate = 5.00;
var fadeTime = 300;
$('.product-quantity input').change( function() {
updateQuantity(this);
});
$('.product-removal button').click( function() {
removeItem(this);
});
function recalculateCart()
{
var subtotal = 0;
$('.product').each(function () {
subtotal += parseFloat($(this).children('.product-line-price').text());
});
var tax = subtotal * taxRate;
var shipping = (subtotal > 0 ? shippingRate : 0);
var total = subtotal + tax + shipping;
$('.totals-value').fadeOut(fadeTime, function() {
$('#cart-subtotal').html(subtotal.toFixed(2));
$('#cart-tax').html(tax.toFixed(2));
$('#cart-shipping').html(shipping.toFixed(2));
$('#cart-total').html(total.toFixed(2));
if(total == 0){
$('.checkout').fadeOut(fadeTime);
}else{
$('.checkout').fadeIn(fadeTime);
}
$('.totals-value').fadeIn(fadeTime);
});
}
function updateQuantity(quantityInput)
{
var productRow = $(quantityInput).parent().parent();
var price = parseFloat(productRow.children('.product-price').text());
var quantity = $(quantityInput).val();
var linePrice = price * quantity;
productRow.children('.product-line-price').each(function () {
$(this).fadeOut(fadeTime, function() {
$(this).text(linePrice.toFixed(2));
recalculateCart();
$(this).fadeIn(fadeTime);
});
});
}
function removeItem(removeButton)
{
var productRow = $(removeButton).parent().parent();
productRow.slideUp(fadeTime, function() {
productRow.remove();
recalculateCart();
});
}
});
Set shipping to zero when subtotal + tax >= 50 (assuming that's the business rule).
var shipping = subtotal > 0 && (subtotal + tax < 50) ? shippingRate : 0;
And then, for display purposes, set the shipping value element to empty when shipping === 0. A ternary operator is one way to do it.
$('#cart-shipping').html(shipping === 0 ? '' : shipping.toFixed(2));

How to calculate total?

I faced a problem for my code and I could not solve it. I have 2 functions, the first one calculates the total and second one discounts the total (if the user write the discount code, it will show the discounted total). But I don't know how to get and call the right value from total to keep it in the second function to calculate the discount because it always shows 0 in the amount. The TOTAL is for the first function and JavaScript code is for the second function.
total = parseInt(TicketsPrice[i].value) * parseInt(NOfTictet);
document.getElementById("total").innerHTML = total;
function discount(coupon) {
var yCoupon = "winner1";
var price = Number(document.getElementById('total').innerHTML);
var amount;
var input = document.getElementById('discount').value;
if (input == coupon) {
amount = price || 0 * 0.25;
document.getElementById("Offerprice").innerHTML = amount;
} else {
alert("Invalid");
}
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>
Something like this?
function discount() {
var coupon = "winner1";
var price = Number(document.getElementById('total').value);
var input = document.getElementById('discount').value;
if (input == coupon) {
var amount = price * (1 - .25) // 25% off coupon
document.getElementById("Offerprice").innerHTML = amount;
} else {
document.getElementById("Offerprice").innerHTML = 'Invalid coupon'
}
}
<div>Total: <input id="total"></div>
<div>Coupon: <input id="discount"></div>
<button onclick="discount()"> discount</button>
<p><span id ="Offerprice"></span></p>
You have several issues in your code. Here is a working version. I hardcoded the total only for testing because I don't know the HTML for your tickets:
var total = 500; //This is only for testing.
document.getElementById("total").innerHTML = total;
function discount() {
var coupon = "winner1";
var price = Number(document.getElementById('total').innerHTML);
var input = document.getElementById('discount').value;
if (input == coupon) {
var amount = price * 0.75; //discount of 25%
document.getElementById("Offerprice").innerHTML = amount;
} else {
alert("Invalid");
}
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>

jquery calculate total amount of bill

I have 3 text fields in my form. 1st one takes value of quantity in the bill 2nd one takes value of price of per unit item and 3rd one takes the value of applicable taxes. I am displaying the final bill amount in the 4th text field. I've tried the following code:
$(document).ready(function () {
$('#Quantity, #Rate, #TaxAmount').keyup(function () {
var total = 0.0;
var qty = $('#Quantity').val();
var rate = $('#Rate').val();
var tax = ('#TaxAmount').val();
var amount = (qty * rate);
total = tax + amount;
$('#TotalAmount').val(total);
});
});
after running the code nothing is being displayed in the 4th textbox with id of TotalAmount. Unable to figure out what is the problem. Somebody please guide.
Firstly, you were missing $ in the var tax line.
That aside, you'll need to use parseFloat to convert the strings you get from .val() to numbers, to be able to do arithmetic on them.
$(document).ready(function() {
var $fields = $('#Quantity, #Rate, #TaxAmount');
$fields.keyup(function() {
var qty = parseFloat($('#Quantity').val());
var rate = parseFloat($('#Rate').val());
var tax = parseFloat($('#TaxAmount').val());
var amount = (qty * rate);
var total = total = tax + amount;
$('#TotalAmount').val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Quantity" placeholder="Quantity"> *
<input id="Rate" placeholder="Rate"> +
<input id="TaxAmount" placeholder="Tax"> =
<input id="TotalAmount" readonly>
You forgot the $ sign before ('#TaxAmount'):
$(document).ready(function () {
$('#Quantity, #Rate, #TaxAmount').keyup(function () {
var total = 0;
var qty = $('#Quantity').val();
var rate = $('#Rate').val();
var tax = $('#TaxAmount').val(); // here
var amount = (qty * rate);
total = tax + amount;
$('#TotalAmount').val(total);
});
});

Calculate the price of the items, depending on its quantity

I'm trying to make block with the prices. The unit price varies depending on its quantity of units. For example:
Quantity — Price for each
1____________________$110
10___________________$105
20___________________$100
...
Number of items:__
Total:
Price for each:
There is a need to write a the text field into which the user enters the number of items, and everything is recalculating and summing on the fly.
Here is my realization of this task:
var price1 = 110,
price2 = 105,
price3 = 100,
qty1 = 1,
qty2 = 10,
qty3 = 20;
function conversion(val) {
var div = document.getElementById("div"),
price = document.getElementById("price");
if (isNaN(val)) {
div.innerHTML = "";
price.innerHTML = "";
} else {
switch (true) {
case (val <= 0):
{
div.innerHTML = "";
price.innerHTML = "";
break;
}
case (val >= qty1 && val < qty2):
{
div.innerHTML = val * price1;
price.innerHTML = price1;
break;
}
case (val >= qty2 && val < qty3):
{
div.innerHTML = val * price2;
price.innerHTML = price2;
break;
}
case (val >= qty3):
{
div.innerHTML = val * price3;
price.innerHTML = price3;
break;
}
}
}
}
<div>
Quantity — Price for each
</div>
<div>
<div>1 — $110</div>
<div>10 — $105</div>
<div>20 — $100</div>
</div>
<div>
Number of items:
<div>
<input id="txt" onblur="conversion(this.value)" onchange="conversion(this.value)" onkeypress="conversion(this.value)" onkeyup="conversion(this.value)" type="number">
</div>
</div>
<div>
Total:
<div id="div"></div>
</div>
<div>
Price for each:
<div id="price"></div>
</div>
How it can be properly implemented, taking into account the fact that the lines with the quantity and unit price can be from one to infinity (values are taken from the database)?
I think it is possible to record the price and quantity in data-atributes and parse it with JS. Like this:
...
<div data-quantity="10" data-price="105">
<span class="quantity">10</span>
<span class="price">105</span>
</div>
...
Thanks!
Using the data attribute is indeed a solution:
console.log(document.getElementById("test").dataset)
<div data-quantity="10" data-price="105" id="test">
<span class="quantity">10</span>
<span class="price">105</span>
</div>
It's not fully compatible with previous IE version though, so be careful with it.
I would however suggest that you look for a way of moving your calculations away from the DOM to speed up your calculations.
For instance, parsing the data to a JavaScript object and doing the calculations there would save you some DOM trips and thus speed:
console.clear();
//markup for product
function Product(name) {
return {
//Name of product
name : name,
//List of price ranges (populated later)
prices : [
],
//method for adding a price
newPrice : function newPrice(quantity, cost) {
//Push new price unto list
this.prices.push({
quantity : quantity,
cost : cost
});
//Sort list
this.prices = this.prices.sort(function (a, b) {
return a.quantity - b.quantity
});
},
//Get the price for a variable quantity of this product
get : function (quantity) {
//Loop through prices to find the most matching
var price = 0;
for (var i = 0; i < this.prices.length; i++) {
if (this.prices[i].quantity <= quantity) {
price = this.prices[i].cost;
} else {
break;
}
}
console.log('price per unit:', price, 'price for all', quantity, 'units:', price * quantity)
}
};
} //Make an instance
var myHotProduct = new Product('Fancy pants');
//Add some prices
myHotProduct.newPrice(0, 110);
myHotProduct.newPrice(10, 105);
myHotProduct.newPrice(20, 100);
//get some quantities
myHotProduct.get(0);
myHotProduct.get(1);
myHotProduct.get(9);
myHotProduct.get(10);
myHotProduct.get(19);
myHotProduct.get(20);
//Log everything we know about our product
console.log(myHotProduct);
Now you can get your prices as arrays and modify them outside of the limitations of data-.

Limit number of clicks on radio button and multiply by a number

As you can see in the jsfiddle, when the #CreditCard radio button is clicked, the Total is multiplied by 1.02 and the Total is updated.
The problem is that the same button can be clicked multiple times and the number keeps multiplying.
I want to limit the number of times a button can be clicked to 1, but also want to be able to switch between Debit card and Credit card. (so when the other button is clicked, the limit is reset to 0?)
Any help is much appreciated.
https://jsfiddle.net/n52fy9am/2/
html
Total: <span id="totalPrice">£154.67</span>
<br>
<form>
<input id="DebitCard" type="radio" name="payment" checked>
<label for="DebitCard">Debit Card</label>
<br>
<input id="CreditCard" type="radio" name="payment">
<label for="CreditCard">Credit Card (2% extra)</label>
<br>
</form>
js
// credit card 2% surcharge
$('#CreditCard').on("click", function() {
var totalPrice = parseFloat($('#totalPrice').text().replace(/([^0-9\\.])/g, ""));
var surcharge = (totalPrice * 1.02).toFixed(2);
// Update total
$('#totalPrice').html("£" + surcharge);
});
// remove 2%
$('#DebitCard').on("click", function() {
var totalPrice = parseFloat($('#totalPrice').text().replace(/([^0-9\\.])/g, ""));
var surcharge = (totalPrice * 0.98).toFixed(2);
// Update total
$('#totalPrice').html("£" + surcharge);
});
Just use a flag to do it. Change the flag when radio button clicked. So that you can control whether to do the calculation or not.
Also, because you round it with toFixed(2), the decimal part of the number will be messed up when you do the calculation. So use a variable to store the initial value. Put it back when debitCard button is pressed.
var isCreditCard = false;
var initialPrice = 154.67;
$('#totalPrice').html("£" + initialPrice.toString());
// credit card 2% surcharge
$('#CreditCard').on("click", function() {
if (!isCreditCard) {
var totalPrice = parseFloat($('#totalPrice').text().replace(/([^0-9\\.])/g, ""));
var surcharge = (totalPrice * 1.02).toFixed(2);
// Update total
$('#totalPrice').html("£" + surcharge);
isCreditCard = true;
}
});
// remove 2%
$('#DebitCard').on("click", function() {
if (isCreditCard) {
// Update total
$('#totalPrice').html("£" + initialPrice.toString());
isCreditCard = false;
}
});
I took your JS fiddle and turned into a stack snippet ;)
I modified the code and placed comments wherever necessary.
I store initial count values that get incremented on every click, if that number exceeds 0 then the function gets cancelled, this remains true until the other radio is checked which resets the previously clicked one.
$(function() {
// keep count of n times clicked
var creditCardCount = 0;
var debitCardCount = 0;
// credit card 2% surcharge
$('#CreditCard').on("change", function() {
// if amount is greater or equal to 1 then abort the function
if (creditCardCount > 0) {
return false;
}
var totalPrice = parseFloat($('#totalPrice').text().replace(/([^0-9\\.])/g, ""));
var surcharge = (totalPrice * 1.02).toFixed(2);
// Update total
$('#totalPrice').html("£" + surcharge);
// increment credit card count
creditCardCount++;
// reset the other option to 0
debitCardCount = 0;
});
// remove 2%
// do the same here but for the opposite cards
$('#DebitCard').on("change", function() {
if (debitCardCount > 0) {
return false;
}
var totalPrice = parseFloat($('#totalPrice').text().replace(/([^0-9\\.])/g, ""));
var surcharge = (totalPrice * 0.98).toFixed(2);
// Update total
$('#totalPrice').html("£" + surcharge);
debitCardCount++;
creditCardCount = 0;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Total: <span id="totalPrice">£154.67</span>
<br>
<form>
<input id="DebitCard" type="radio" name="payment" checked>
<label for="DebitCard">Debit Card</label>
<br>
<input id="CreditCard" type="radio" name="payment">
<label for="CreditCard">Credit Card (2% extra)</label>
<br>
</form>
I suggest you simplify your code. Check demo - Fiddle:
$(function() {
var lastRadioClicked = 'DebitCard',
canClick = true;
$('[name="payment"]').on("click", function() {
var surchargePercent;
if (lastRadioClicked === this.id) {
if (canClick) {
if (this.id === 'DebitCard') {
// debit
surchargePercent = 0.98;
} else {
// credit
surchargePercent = 1.02;
}
canClick = false;
var totalPrice = parseFloat($('#totalPrice').text().replace(/([^0-9\\.])/g, ""));
var surcharge = (totalPrice * surchargePercent).toFixed(2);
// Update total
$('#totalPrice').html("£" + surcharge);
}
} else {
lastRadioClicked = this.id;
canClick = true;
}
});
});

Categories

Resources