jquery calculate total amount of bill - javascript

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);
});
});

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 price, total, shipping and vat in a cart system

Case:
I'm trying to create a Cart system that will Calculate the price based on the quantity of ordered items, then will be sum with the shipping amount and finally calculate the grand total adding VAT price.
Code:
$(document).ready(function(){
update_amounts();
$('.qty').change(function() {
update_amounts();
});
});
function update_amounts()
{
var sum = 0.0;
$('#myTable > tbody > tr').each(function() {
var qty = $(this).find('option:selected').val();
var price = $(this).find('.price').val();
var amount = (qty*price)
sum+=amount;
$(this).find('.amount').text(''+amount);
});
//calculate the total to sum
$('.total').val(sum);
//calculate total + shipping and add VAT
var shipping = $(this).find('.shipping').val();
var total = $(this).find('.total').val();
var vat = $(this).find('.vat').val();
//calculate vat
var vat_amount = ((total, 10) * 100);
//calculate grand total
var total_shipping = (total+shipping);
var ship_amount = (total_shipping+vat_amount);
sum+=ship_amount;
$('.grandTotal').val(sum);
}
Behaviour:
This don't work even if I've taken the first part of a working fiddle, can't see data changing on item total price, and can't calculate the grand total too.
Expected Behaviour:
When an user click on the Q.ty select:
- total of the row must to be updated calculating price * qty
- total of rows price must to be updated
- the sum of total of row price must to be added to shipping price
- finally the vat, calculated on sum of total row must return the grand total.
Fiddle:
Here is a full fiddle with the html part adapted (I'm using a PHP script to populate the table) https://jsfiddle.net/a1o2nmw8/1/
Thanks to all who can collaborate.
$(document).ready(function(){
update_amounts();
$('.qty').change(function() {
update_amounts();
});
});
function update_amounts()
{
var sum = 0.0;
$('#myTable > tbody > tr').each(function() {
var qty = $(this).find('option:selected').val();
var price = $(this).find('.price').text();
var amount = (qty*price)
sum+=amount;
$(this).find('.amount').text(''+amount);
});
//calculate the total to sum
$('.total').val(sum);
//calculate total + shipping and add VAT
var shipping = $('.shipping').val();
var total = $('.total').val();
var vat = $('.vat').val();
//calculate vat
var vat_value = ((total*vat)/100);
//calculate grand total
sub_total = (parseFloat(total)+parseFloat(shipping)).toFixed(1);
var grand_total = (parseFloat(sub_total)+parseFloat(vat_value )).toFixed(1);
$('.grandTotal').val(grand_total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table class="table table-striped" id="myTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Desc</th>
<th>Q.ty</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>product</td>
<td>description</td>
<td><select class="qty" value="500">
<option value="500">500</option>
<option value="1000">1000</option>
</select></td>
<td><span class="price">50.0</span></td>
<td><span class="total">0.0</span></td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-sm-3 col-sm-offset-9">
<table class="table table-striped">
<tr>
<td>Total</td>
<td><input type="text" class="total input" value="0.0" > €</td>
</tr>
<tr>
<td>Shipping</td>
<td><input type="text" class="shipping input" value="30.0" > €</td>
</tr>
<tr>
<td>VAT</td>
<td><input type="text" class="vat input" value="22" disabled> %</td>
</tr>
<tr>
<td><strong>Grand Total</strong></td>
<td><strong><input type="text" class="grandTotal input" value="0.0" disabled> €</strong></td>
</tr>
</table>
</div>
On the Example you posted you are not using any library. Try this one, it changes for me.
UPDATED: also added .toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}); for the Grand Total.
$(document).ready(function(){
update_amounts();
$('.qty').change(function() {
update_amounts();
});
});
function update_amounts()
{
var sum = 0.0;
$('#myTable > tbody > tr').each(function() {
var qty = $(this).find('option:selected').val();
var price = $(this).find('.price').text();
var amount = (qty*price)
sum+=amount;
$(this).find('.amount').html(''+amount);
});
//calculate the total to sum
$('.total').val(sum);
//calculate total + shipping and add VAT
var shipping = $('.shipping').val();
var total = $('.total').val();
var vat = $('.vat').val();
//calculate vat
var vat_amount = ((total*vat)/100);
//calculate grand total
var total_shipping = (parseFloat(total)+parseFloat(shipping));
var grand_total = (parseFloat(total_shipping)+parseFloat(vat_amount)).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});;
$('.grandTotal').val(grand_total);
}
https://jsfiddle.net/a1o2nmw8/10/
Can you try this???
$(document).ready(function(){
update_amounts();
$('.qty').change(function() {
update_amounts();
});
});
function update_amounts()
{
var sum = 0.0;
$('#myTable > tbody > tr').each(function() {
var qty = $(this).find('option:selected').val();
var price = $(this).find('.price').html();
var amount = (qty*price)
sum+=amount;
console.log("sum"+sum)
$('.amount').html(''+amount);
});
//calculate the total to sum
$('.total').val(sum);
//calculate total + shipping and add VAT
var shipping = $('.shipping').val();
var total = $('.total').val();
var vat = $('.vat').val();
//calculate vat
var vat_amount = ((total, 10) * 100);
//calculate grand total
var total_shipping = (total+shipping);
var ship_amount = (total_shipping+vat_amount);
sum+=ship_amount;
$('.grandTotal').val(sum);
}
For select span value, you need to use "text()", then replace
var price = $(this).find('.price').val();
By :
var price = $(this).find('.price').text();
Then :
var shipping = $(this).find('.shipping').val();
var total = $(this).find('.total').val();
var vat = $(this).find('.vat').val();
You don't need to use $(this) here, just remove and use selector as follow :
var shipping = $('.shipping').val();
var total = $('.total').val();
var vat = $('.vat').val();
And at the end, add parseFloat :
var ship_amount = parseFloat(total_shipping+vat_amount);
otherwise he just concat as a string.
Working example
The only thing you need to do is change .val() function with .text().
.val() will work fine with combobox, textboxes etc. If you want to get the text use .text().
Before doing mathematical operations convert the text to number. For that you can use parsefloat() or parseInt() methods.

Reset total sum if input changes with jquery change event

I have a list of inputs that i'll be using to set values (0 to 100).
The total values from those inputs can't be more than 100, i have this done and it's working, but i need a way to subtract the total if i change one of those inputs and the total becomes < 100
Here's one example for what i have so far:
var soma_total = 0;
jQuery(function($){
$('input[type=text]').each(function () {
$(this).change(function(){
var valor = $(this).val();
valorPorcentagem = valor;
eE = procPorcentagem(valorPorcentagem);
eE = Math.ceil(eE);
valorPorcentagem = parseInt(valorPorcentagem);
if((parseInt(valorPorcentagem) + soma_total) > 100)
valorPorcentagem = 100 - soma_total;
$(this).val(valorPorcentagem);
soma_total += valorPorcentagem;
console.log(soma_total);
$('#final_sum').append('<li>'+soma_total+'</li>');
});
});
});
function procPorcentagem(entradaUsuario){
var resultadoPorcem = (entradaUsuario * 48) / 100;
return resultadoPorcem;
}
JSFiddle
Help please, thanks!
This demo might give you an idea on how to proceed:
$(function() {
$(':text').val(0).on('change', function(e) {
var i = $(':text'),
total = 0;
i.each(function() {
total += +this.value;
});
if( total > 100 ) {
this.value -= (total - 100);
}
total = 0;
i.each(function() {
total += +this.value;
});
$('#final_sum').text( total );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<div id="final_sum">0</div>

JQuery Column Calculations

I need some assistance with this code:
http://jsfiddle.net/N5xTJ/1/
The last column already is dynamic through jQuery, which calculates "Packs QTY" x "Price", then totals on the bottom.
I need help doing the calculation for total QTY based on <TD CLASS="QTY"> and it will show results in totalsqty.
Also for TotalUnits Needs to calculate "Qty" X "Units Per Pack" and show in "Total Units".
JS that is currently doing the totals for #Total Price:
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $row=$(this);
var $qnt = $(this).find(".qty");
var cost = $row.data('unit_price');
var sum = cost * parseFloat($qnt.val());
$(this).find("td").eq(5).text('$' +sum);
$overall += sum;
});
$("#total").text('$' +$overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup', ca);
});
Try this fiddle: http://jsfiddle.net/N5xTJ/4/
I've updated your existing code, to accommodate totalUnits and totalQty.
Code (with comments):
function ca() {
var $overall = 0,
totalQty = 0,
totalUnits = 0;
$("tr.sum").each(function() {
var $row = $(this),
qnt = parseInt($(this).find("input.qty").val()),
cost = $row.data('unit_price'),
sum = cost * qnt,
upp = parseInt($row.find('.upp').text());
$row.find('span.t-units').text(upp * qnt);
$(this).find("td").eq(5).text('$' + sum);
totalQty += qnt;
totalUnits += parseInt($row.find('span.t-units').text());
$overall += sum;
});
$("#total").text('$' + $overall);
$('#totalqty').text(totalQty);
$('#totalunits').text(totalUnits);
}
$(function() {
ca();
$('input.qty').bind('change keyup', ca);
});​
I've also cleaned up the code a bit, so have a look and let me know if you have questions.

Categories

Resources