Discount and Tax Calculator in JS using jQuery Tutorial

Introduction

In this tutorial, we will tackle How to Calculate the Discount and Tax Amount for your sales transaction feature in your web applications using JavaScript and jQuery Library. This tutorial aims to give IT/CS students or new programmers a reference or guide to learn some new ways or techniques for their future projects.

As we know, sales transactions/cashiering apps/POS are one of the most important features or processes needed for business software or application. These features include the list of products and the total summary which commonly contains discount and tax data along with grand total computation. Using JavaScript and jQuery, you can calculate both discount and tax amount from the sub-total and percentage entered which also makes your software or application more interactive and gives you users a better experience of using the software.

What is jQuery?

jQuery is a JavaScript Library that is fast, compact, and feature-rich. It greatly simplifies tasks like traversing and manipulating HTML documents, handling events, creating animations, and using Ajax thanks to an intuitive API that is compatible with a wide range of browsers.

How to Calculate Discount and Tax Amount using jQuery?

Now, I will show the best way I can think of for calculating the Discount and Tax amount using jQuery. Here I will be providing a snippet that outputs a simple web application that demonstrates our main goal for this tutorial.

Here's the sample snippet that can be found on the source code. It contains the computation process and the formula used to get the result we need for our app.

`var perc = \$(this).val()    perc = perc > 0 ? perc : 0; var sub_total =  \$('#sub_total').text() var disc = parseFloat(perc / 100) * parseFloat(sub_total) ;\$('#disc_amount').text(disc.toFixed(3))`

Let's start the coding part

The below snippets are the script to output a simple cashiering web application developed using HTML, CSS, Bootstrap, JS, and jQuery. Follow or copy and modify the script the way you wanted to practice your own skill and gain new knowledge for your future project

Page Interface

This is an HTML Script saved and named "index.html". It contains all the HTML elements used for the application user interface The script I created below uses CDN for loading the Bootstrap Framework and jQuery Library which requires an internet connection to work properly. Otherwise, you can download the files on their respective official website and store them in your source code directory.

`<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>JS Discount & Tax Calculator</title>    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">    <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script></head><body class="bg-dark bg-opacity-50">    <div class="container my-4">            <div class="mx-auto width-auto">                <h1 class="text-center text-light"><b>JS Discount & Tax Calculator using jQuery</b></h1>                <hr class="border-light">            </div>            <div class="col-lg-12 col-md-12 col-sm-12 my-2">                <div class="card rounded-0">                    <div class="card-body">                        <div class="container-fluid">                            <h4><b>Sample Item List with Total Summary</b></h4>                            <hr>                            <div id="item-list" class="list-group">                                <div class="list-group-item">                                    <div class="d-flex">                                        <div class="px-1 col-3 text-center">                                            <label for="" class="text-muted">Product</label>                                        </div>                                        <div class="px-1 col-3 text-center">                                            <label for="" class="text-muted">Quantity</label>                                        </div>                                        <div class="px-1 col-3 text-center">                                            <label for="" class="text-muted">Unit Price</label>                                        </div>                                        <div class="px-1 col-3 text-center">                                            <label for="" class="text-muted">Tototal</label>                                        </div>                                    </div>                                </div>                                <div class="list-group-item">                                    <div class="d-flex">                                        <div class="px-1 col-3">                                            <input type="text" class="form-control rounded-0" value="Sample Item 101" name="item_name[]">                                        </div>                                        <div class="px-1 col-3">                                            <input type="number" class="form-control rounded-0 text-end" value="3" name="quantity[]">                                        </div>                                        <div class="px-1 col-3">                                            <input type="number" step="any" class="form-control rounded-0 text-end" value="15" name="unit_price[]">                                        </div>                                        <div class="px-1 col-3">                                            <input type="text" class="form-control rounded-0 text-end" value="0" readonly name="item_total[]">                                        </div>                                    </div>                                </div>                                <div class="list-group-item">                                    <div class="d-flex">                                        <div class="px-1 col-3">                                            <input type="text" class="form-control rounded-0" value="Sample Item 102" name="item_name[]">                                        </div>                                        <div class="px-1 col-3">                                            <input type="number" class="form-control rounded-0 text-end" value="4" name="quantity[]">                                        </div>                                        <div class="px-1 col-3">                                            <input type="number" step="any" class="form-control rounded-0 text-end" value="20" name="unit_price[]">                                        </div>                                        <div class="px-1 col-3">                                            <input type="text" class="form-control rounded-0 text-end" value="0" readonly name="item_total[]">                                        </div>                                    </div>                                </div>                                <div class="list-group-item">                                    <div class="d-flex">                                        <div class="px-1 col-3">                                            <input type="text" class="form-control rounded-0" value="Sample Item 104" name="item_name[]">                                        </div>                                        <div class="px-1 col-3">                                            <input type="number" class="form-control rounded-0 text-end" value="5" name="quantity[]">                                        </div>                                        <div class="px-1 col-3">                                            <input type="number" step="any" class="form-control rounded-0 text-end" value="60" name="unit_price[]">                                        </div>                                        <div class="px-1 col-3">                                            <input type="text" class="form-control rounded-0 text-end" value="0" readonly name="item_total[]">                                        </div>                                    </div>                                </div>                            </div>                            <hr>                            <div class="list-group rounded-0" id="total_summary">                                <div class="list-group-item">                                    <div class="d-flex justify-content-end">                                        <div class="col-auto pe-3">Sub Total</div>                                        <div class="col-3 text-end fw-bold" id="sub_total">0.00</div>                                    </div>                                </div>                                <div class="list-group-item">                                    <div class="d-flex justify-content-end">                                        <div class="col-auto pe-3">Discount %</div>                                        <div class="col-3 text-end fw-bold"><input type="number" step="any" min="0" max="100" value="0" id="disc_perc" class="form-control text-end"></div>                                    </div>                                </div>                                <div class="list-group-item">                                    <div class="d-flex justify-content-end">                                        <div class="col-auto pe-3">Discount Amount</div>                                        <div class="col-3 text-end fw-bold" id="disc_amount">0.00</div>                                    </div>                                </div>                                <div class="list-group-item">                                    <div class="d-flex justify-content-end">                                        <div class="col-auto pe-3">Tax %</div>                                        <div class="col-3 text-end fw-bold"><input type="number" step="any" min="0" max="100" value="0" id="tax_perc" class="form-control text-end"></div>                                    </div>                                </div>                                <div class="list-group-item">                                    <div class="d-flex justify-content-end">                                        <div class="col-auto pe-3">Tax Amount</div>                                        <div class="col-3 text-end fw-bold" id="tax_amount">0.00</div>                                    </div>                                </div>                                <div class="list-group-item">                                    <div class="d-flex justify-content-end">                                        <div class="col-auto pe-3">Total</div>                                        <div class="col-3 text-end fw-bold" id="total">0.00</div>                                    </div>                                </div>                            </div>                        </div>                    </div>                </div>            </div>    </div></body><script src="script.js"></script></html>`

Creating the Main Script

The following script is the code that demonstrates the topic for this tutorial. It is a JavaScript file named "script.js" and loaded on the index or app's main page file.

`\$(document).ready(function(){     // Calculating Item Total Price    \$('[name="quantity[]"], [name="unit_price[]"]').on('input, change', function(){        var qty = \$(this).closest('.list-group-item').find('[name="quantity[]"]').val()        var price = \$(this).closest('.list-group-item').find('[name="unit_price[]"]').val()        qty = qty > 0 ? qty : 0 ;        price = price > 0 ? price : 0 ;        var total = qty * price;        \$(this).closest('.list-group-item').find('[name="item_total[]"]').val(total)        sub_total()    })     // Calculating Sub Total    function sub_total(){        var sub_total = 0        \$('[name="item_total[]"]').each(function(){            sub_total += parseFloat(\$(this).val())        })        \$('#sub_total').text(sub_total.toFixed(3))        calc_total()     }     \$('[name="quantity[]"]').trigger('change')     // calculating discount amount from percentage    \$('#disc_perc').on('change', function(){        var perc = \$(this).val()            perc = perc > 0 ? perc : 0;         var sub_total =  \$('#sub_total').text()         var disc = parseFloat(perc / 100) * parseFloat(sub_total) ;        \$('#disc_amount').text(disc.toFixed(3))        calc_total()    })    // calculating discount amount from percentage    \$('#tax_perc').on('change', function(){        var perc = \$(this).val()            perc = perc > 0 ? perc : 0;         var sub_total =  \$('#sub_total').text()         var tax = parseFloat(perc / 100) * parseFloat(sub_total) ;        \$('#tax_amount').text(tax.toFixed(3))        calc_total()     })     // calculate Grand Total    function calc_total(){        var sub_total =  \$('#sub_total').text()        var disc =  \$('#disc_amount').text()        var tax =  \$('#tax_amount').text()         var total = (parseFloat(sub_total) - parseFloat(disc)) + parseFloat(tax)        \$('#total').text(total.toFixed(3))    }})`

Output Snapshot

The image below is the sample snapshot of the interface of this sample application.

DEMO VIDEO

That's it! You can now test the application and check if it achieves our main goal for this tutorial which is Calculating the Discount and Tax Amount using JavaScript and jQuery. I also provided the working source code I created for this tutorial. Feel free to download it and modify it as you wanted. The download button is located below this article.

I hope this tutorial will help you with what you are looking for and that you'll find it useful for your current or future projects. Explore more on this website for more Tutorials and Free Source Codes.