You are viewing limited content. For full access, please sign in.

Question

Question

Javascript to calculate tax

asked on March 1, 2016 Show version history

Hello, I am fairly new at javascript and am trying to complete, what I think, is a fairly simple task....  I am pounding my head trying to figure it out.

 

I have a form that uses a table with quantity and price then total for the line.   This part works and below is the code I am using.  The subtotal of all table lines populates a field outside the table called "Subtotal".  I am selecting the province at the top of the form for the address and that province field fills a hidden field called "Tax Percentage" with the decimal version of the tax rate.  (ie. 0.13).  I am looking to have the javascript calculate the appropriate tax amount using the "Subtotal" field (CSS:  subtotal) multiply it with the populated "Tax Percentage" field (CSS: taxpercent) then put the calculated tax amount in a field called "Tax" (CSS: tax) and the total amount in the "Total" field (CSS: total).   

List of CSS classes:  

Field:   Subtotal      CSS: subtotal

Field:   Tax Percentage      CSS: taxpercent

Field:   Tax              CSS: tax

Field:   Total           CSS:  total

$(document).ready(function () {
$('.cf-table-block').on('blur', 'input', sumtotal);
$('.tax').on('blur', 'input', sumtotal);
function sumtotal() {
	var sum = 0;
$('.cf-table-block tbody tr').each(function () {
	var s = 0;
	s = parseNumber($(this).find('.price input').val()) * parseNumber($(this).find('.quantity input').val());
$(this).find('.cost input').val(s);
	sum += s;
$('.subtotal input').val(sum);
});
}
function parseNumber(n) {
var f = parseFloat(n); //Convert to float number.
return isNaN(f) ? 0 : f; //treat invalid input as 0;
}
});

 

0 0

Answer

SELECTED ANSWER
replied on March 1, 2016

You don't appear to have any code that does this calculation in your example. Why not insert some code into the end of your sumtotal function to do just that? This will run whenever your table gets changed.

function sumtotal() {
	var sum = 0;
$('.cf-table-block tbody tr').each(function () {
	var s = 0;
	s = parseNumber($(this).find('.price input').val()) * parseNumber($(this).find('.quantity input').val());
$(this).find('.cost input').val(s);
	sum += s;
$('.subtotal input').val(sum);
$('.tax input').val(parseNumber($('.taxpercent input').val())*sum);
$('.total input').val(parseNumber($('.tax input').val())+sum);
});
}

 

1 0

Replies

replied on March 2, 2016 Show version history

Thanks for the quick reply Scott.  

I did forget to add the code I was trying in a separate block.  In my limited knowledge of javascript I was making this WAY to complicated.  Your simple answer did the trick and works like a charm.

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.