views:

31

answers:

3

How to apply Tax, discount to subtotal and calculate grand total??

I have these paragraphs with the following ID's

<p id="subtotal">15000</p>
<p id="tax">10</p> // In percentage
<p id="discount">1000</p>
<p id="grandtotal"></p> // Grandtotal will be calculated and displayed here using jquery

The grand total would be 15000 + (1500 //tax) - (1000 //discount) = 15500

How do i calculate this using jQuery?

+2  A: 
var subtotal = parseFloat( $('#subtotal').text() );
...

$('#grandtotal').text( grandTotal );

The rest is vanilla javascript, other than setting or getting.

Stefan Kendall
How to calculate the percentage??? :D :)
Roccos
A: 

First off, total abuse of the paragraph element <p>. Instead, use the folling:

HTML

<div id="subtotal-and-taxes">
    <var id="subtotal">15000</var>
    <var id="tax">10</var> // In percentage
    <var id="discount">1000</var>
    <var id="grandtotal"></var> // Grandtotal will be calculated and displayed here using jquery
    <!-- or use span elements -->
</div>

CSS

#subtotal-and-taxes var {
    display:block
    margin-top:5px;
    margin-bottom:5px;
}

Next, you can use jQeury to get references to those elements and read their contents with the html() function:

var subtotal = $("#subtotal-and-taxes #subtotal").html();
var tax = $("#subtotal-and-taxes #tax").html();
var discount = $("#subtotal-and-taxes #discount").html();

and then use non-jQuery JavaScript to calculate the value for grandtotal. Unfortunately, your equation is a little confusing so I won't spell it out for you.

LeguRi
+1  A: 
var subtotal = parseFloat( $('#subtotal').text());
var taxRate = parseFloat( $('#tax').text());
var disc = parseFloat( $('#discount').text());

var taxAmount = subtotal * (taxRate/parseFloat("100")); //15000 * .1

var yourGrandTotal = subtotal + (taxAmount) - (disc);

//update div with the val
$('#grandtotal').text(yourGrandTotal);
p.campbell
Thank you :) Exactly what i was looking for, though other answers are correct as well.
Roccos