VAT / Tax Calculator with jQuery
Download Exercise FilesDemoIn this exercise we will build the VAT / Tax calculator, which allows us to provide the amount and calculate the tax rate and the total / sub-total, based on the selection of tax rate and whether the entered amount is tax inclusive or not.
I believe you've already downloaded the exercise files - if not please do it now and put the entire content into the root of your project.
Open the index.html file and in between the opening and closing body tags create a structure of our form. I'm going to support it with the table as I personally find them very useful when it comes to creating layouts of the forms:
<form id="calculator" method="post"> <table class="tbl_insert"> <tr> <th><label for="amount">Amount:</label></th> <td> <input type="text" name="amount" id="amount" value="" class="field" /> </td> </tr> <tr> <th><label for="tax_included">Vat included?:</label></th> <td> <input type="checkbox" name="tax_included" id="tax_included" /> </td> </tr> <tr> <th><label for="tax">VAT/Tax rate:</label></th> <td> <select name="tax" id="tax" class="select"> <option value="20">20%</option> <option value="17.5">17.5%</option> <option value="15">15%</option> </select> </td> </tr> <tr> <th><label for="tax_amount">VAT/Tax:</label></th> <td> <input type="text" name="tax_amount" id="tax_amount" value="0.00" class="field" disabled="disabled" /> </td> </tr> <tr> <th><label for="total_amount">Total:</label></th> <td> <input type="text" name="total_amount" id="total_amount" value="0.00" class="field" disabled="disabled" /> </td> </tr> </table> </form>
As you can see we have the field called amount, which is where you will be able to type in the initial amount, then we have a checkbox tax_included, which indicates whether the entered amount includes tax or not. Next we have the dropdown menu tax, which stores a few, default VAT / Tax rates - you can add to it to match your country's specific tax rates. After vat rate we have two text fields - both of them disabled as we do not want visitors to be able to change values inside of them. First field tax_amount will display the VAT / Tax amount and the other total_amount with display a total / sub-total of the calculation depending on whether the initial amount is tax inclusive or not.
Now that we have our form ready, let's open the core.js file, which you'll find inside of the js folder and start by creating the new object called calcObject and three properties of that object called amountNull, which represents the initial value inside of out disabled fields, amountTax, which will store calculated value of the tax and amountTotal, which will store the calculated value of the total / sub-total:
var calcObject = {
amountNull : '0.00',
amountTax : '0.00',
amountTotal : '0.00',
};
Next, after the last property we will create a new method called run:
run : function() {
var amount = $('#amount').val();
var tax = $('#tax').val();
var included = $('#tax_included').is(':checked');
if (amount !== '' && tax !== '') {
if (included) {
var amountNew = amount / ((tax / 100) + 1);
calcObject.amountTax = parseFloat(amount) - parseFloat(amountNew);
calcObject.amountTotal = amountNew.toFixed(2);
} else {
calcObject.amountTax = (amount * tax) / 100;
calcObject.amountTotal = parseFloat(amount) + parseFloat(calcObject.amountTax);
}
$('#tax_amount').val(parseFloat(calcObject.amountTax).toFixed(2));
$('#total_amount').val(parseFloat(calcObject.amountTotal).toFixed(2));
} else {
$('#tax_amount').val(calcObject.amountNull);
$('#total_amount').val(calcObject.amountNull);
}
}
The new, run method starts with creating three variables: amount, tax and included and assign the values for the associated form fields to them. The included variable simply checks whether the tax_included checkbox is checked, which will result in true or false.
Next we check whether the amount and tax variables are not empty and if they are not, then we check whether the tax is included in the initial amount - if so, we calculate the new amount by dividing the initial amount by the tax rate divided by 100 plus one.
The amountTax property is now assigned the new value of the initial amount minus new amount. We are using the parseFloat function to convert text values to numbers in order to perform our calculations.
The amountTotal on the other hand is assigned the new value rounded to 2 decimal places using toFixed function.
If the amount does not include the tax, then we calculate the amountTax by first multiplying the initial amount by tax rate and dividing it by 100.
The amountTotal is then calculated by adding initial amount and the tax total.
If amount or tax variables return null, then we simply put the value assigned to the amountNull property into the two result fields.
Now, that our object is completed, we need to call it on the number of occasions. You most probably already realised that we did not include the submit button. The reason being is because we will calculate all these values as we type the numbers into the first field, check or uncheck the tax inclusion checkbox or change the tax rate.
To call our run method whenever one of those events is triggered type the following right after our object:
$(function() {
$('#amount').keyup(function() {
calcObject.run();
});
$('#tax_included').click(function() {
calcObject.run();
});
$('#tax').change(function() {
calcObject.run();
});
});
Inside of the DOM we have first assigned the keyup event to our amount field, so that when someone types types the amount the values are automatically updated. The click event is assigned to the tax_included checkbox - when someone clicks on the button (checks or uncheck it) the values are also automatically calculated. The same applies to the tax field, which has change event assigned to it.




Franco Musso : @askfranco on Monday, 24th October 2011
Extremely helpful and very clearly explained.
I love the concept of calculating form field 'live' without the need to submit, feels so much slicker and more professional.
I've been looking for a tutorial like this for ages but was stuck with over-complicated full calculator type implementations. This was just what I needed, thanks so much :)
Reply
Sebastian Sulinski : @designtutorials on Monday, 24th October 2011
Hi Franco - thanks for the comment - I'm glad you've found it useful.
Reply
Qaysar Akbar on Saturday, 29th October 2011
Hi Sebastian,
Wondeful example..again done in your fantastic style.
I wanted to know if this can used to add from form fields like below.
For example.
I have a table with the following fields around 4 or 5 rows down
Name
Qty
Price
Line-Total
Would I need to give each individual field a unqiue name and also add these fields with the JS?
Kind Regards
Reply
Sebastian Sulinski : @designtutorials on Saturday, 29th October 2011
Hi Qaysar,
Yes - that's exactly what you'd have to do - then perform calculation based on the values entered to these fields.
Reply
Imran Khan on Wednesday, 30th November 2011
Hello Sebastian,
I'm looking for a simple solution to do some calculations for a form. It's nothing extravagant just a simple form that will take two figures i.e. (5 * 2 = 10) two fields with qty and a total next to them max two or three rows and than I wiould be taking the total qty of this at the end.
How can I get a field to add/multiply two figures together and than get the total from that.
I have been looking for a solution but cannot find any.
Also I was wondering if you would be offering some discounts for your tutorials near to Christmas. Looking to purchase a few of your tutorials.
What type of support is available for Premium tutorials as your feed back always looks positive on the few tutorials I have viewed.
Thanks
Reply
Sebastian Sulinski : @designtutorials on Wednesday, 30th November 2011
Hi Imran,
Thanks for getting in touch.
I'll try to create tutorial on how to do this simple calculator sometime next week.
I will also be sending the new email campaign by the end of this week as we are going to be launching our latest Premium Tutorial on how to build Multilingual CMS this week. This campaign will contain the Xmas discount codes so you will be able to grab yourself a deal if you are planning to purchase some of our tutorials.
With regards to the support - I'm always trying to respond to the inquiries as soon as I can. Obviously Premium tutorials take priority over any other inquiries submitted through our website.
Reply
Imran Khan on Monday, 5th December 2011
Hello Sebastian,
Thank you for your reply.
Can you please let me know when you have created this tutorial as I am really looking forward to it.
Thanks
Reply
Sebastian Sulinski : @designtutorials on Monday, 5th December 2011
Hi Imran,
I should be able to publish it within the next 2 weeks.
Reply
Imran Khan on Thursday, 15th December 2011
Hi Sebastian,
Sorry to bother you but I was wondering if you had a chance to create this tutorials please.
Thanks You
Reply
Sebastian Sulinski : @designtutorials on Thursday, 15th December 2011
Hi Imran,
I have it created as a project, but need to record it - perhaps over the weekend - so it should be on our website sometime next week.
Reply
Sebastian Sulinski : @designtutorials on Tuesday, 27th December 2011
Hi Imran,
The new tutorial on how to create the online calculator has now been published: Online Calculator with jQuery and PHP
Reply
Rakesh on Tuesday, 3rd January 2012
Hello Sebastian,
Sorry my last comment on this was posted on another tutorial - VAT / Tax calculator and not this.
I was asking if you had a resource or tutorial that will help me create a form with some calculations.
I was hoping you can help with that please.
Happy New Year!
Thanks
Reply
Sebastian Sulinski : @designtutorials on Tuesday, 3rd January 2012
Hi Rakesh,
Thank you - Happy New Year to you too.
I've created a tutorial on how to build a calculator, which should help you to build the form - as I thought this was what you were asking for.
Reply
Rakesh on Wednesday, 4th January 2012
Hello Sebastian,
Sorry but this is not what I was talking about as this is a calculator and not sure how this will be able to be changed into a form.
what I was referring to was...
A form with the below fields and around 3-5 rows going down:
Qty * price = Line total (Line total is automatically calculated - Should be blank with no "0" values at all in case they are entered to database so fields that are left blank are not entered)
Qty * price = Line total (Line total is automatically calculated - Should be blank with no "0" values at all in case they are entered to database so fields that are left blank are not entered)
Qty * price = Line total (Line total is automatically calculated - Should be blank with no "0" values at all in case they are entered to database so fields that are left blank are not entered)
Than at the bottom of the form it has the following fields which are automatically calculated as the above form is being filled in.
Sub-Total
VAT
Total
The calculations is the hard part that.
I'm thinking along the lines of the whole project will have 3 main files.
1 page with Form on it
1 JQuery file to do the calculation with Ajax call
1 page to do some basic validation - One field is required with success/error message (similar to Web Form with Jquery $.ajax() and PHP) With indication of what to do next i.e // PROCESS FORM - in case someone wants to save this to database or send via email etc - Not required if not needed)
Any tutorial to help with this is much appreciated.
Thank You
Reply
Sebastian Sulinski : @designtutorials on Wednesday, 4th January 2012
Hi Rakesh,
I'm sorry I misunderstood your initial request. I don't really have that much time to create another one on calculations, but here are a few tips, which might help you to achieve what you're aiming for:
Once you have the form ready, with some help of jQuery create the object and the method, which will trigger on blur() and takes all calculation fields pairs i.e. qty_1 and price_1 - then checks if both have values and if so - performs the calculation and updates the total values. Every time the blur event is triggered you would have to check all of the input fields and make sure that all of them have values, then add them to the array, which you will later send to the PHP script like so:
var calculatorObject = { valuesArray : [], calculate : function() { var qtyOne = $('#qty_1').val(); var priceOne = $('#price_1').val(); var qtyTwo = $('#qty_2').val(); var priceTwo = $('#price_2').val(); var qtyThree = $('#qty_3').val(); var priceThree = $('#price_3').val(); if (qtyOne !== '' && priceOne !== '') { calculatorObject.valuesArray.push({ "name": 'qty_1', "value": 'qtyOne' }); calculatorObject.valuesArray.push({ "name": 'price_1', "value": 'priceOne' }); } // continue doing the same for other fields // call to php jQuery.post('url_to_php_page', calculatorObject.valuesArray, function(data) { // do whatever you wish with the returned 'data' }, 'json'); }, updateBlur : function(obj) { obj.live('blur', function() { calculatorObject.calculate(); }); } }; $(function() { calculatorObject.updateBlur($('.fieldClass')); });I hope this will help you to achieve your goal.
Reply
whiteb0x on Wednesday, 4th April 2012
wow this tutorial blew me away dude thanks
Reply