Auto Calculate Total Price in Javascript

In this blog post, we learn how to auto calculate the total price on input change. This is task is very important when you are but an e-commerce project. where we need real-time calculation of product selection.

auto calculate total in javascript
Auto calculate total price in Javascript

To achieve this task we use getElementById() . It returns an Element object representing the element whose id property matches the specified string.

Make a simple form


    <div class="mb-3">
        <label for="inputProductPrice" class="form-label">Product Price</label>
        <input type="text" class="form-control" id="inputProductPrice" oninput="myFunction()" >
    <div class="mb-3">
        <label for="inputGST" class="form-label">GST</label>
        <input type="number" class="form-control" id="inputGST" oninput="myFunction()">
    <div class="mb-3">
        <label for="inputDelivery" class="form-label">Delivery Charge</label>
        <input type="number" class="form-control" id="inputDelivery" oninput="myFunction()">

    <h4>Total Price: <span id="totalPrice">0</span></h4>


    function myFunction() {
        var price = document.getElementById("inputProductPrice").value;
        var gst = document.getElementById("inputGST").value;
        var delivery = document.getElementById("inputDelivery").value;
        var total = +price + +gst + +delivery;
        document.getElementById("totalPrice").innerHTML = total;

Here I wrote a simple js code. To get the value of the input boxes and sum them in a total variable. And at the last I used innerHTML, It is used to gets or sets the HTML or XML markup contained within the element.

I hope this post will be helpful for you.