How to calculate two textbox values in javascript?

In this blog post, we learn how to calculate two textbox values in javascript. Often two or more input values need to be calculated in projects.

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

auto calculate total in javascript
auto calculate total in javascript


<!DOCTYPE html>
      <title>Display Data in Textarea</title>
         <div class="mb-3">
            <label for="inputProductPrice" class="form-label">Product Price</label>
            <input type="text" class="form-control" id="inputProductPrice">
         <div class="mb-3">
            <label for="inputGST" class="form-label">GST</label>
            <input type="number" class="form-control" id="inputGST">
         <div class="mb-3">
            <label for="inputDelivery" class="form-label">Delivery Charge</label>
            <input type="number" class="form-control" id="inputDelivery">
         <h4>Total Price: <span id="totalPrice">0</span></h4>
      <input type="button" value="calculate Data" onclick="myFunction()" />


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 is simple javascript code. Javascript function work after hitting the button and display the calculated data using innerHTML. The Element property innerHTML gets or sets the HTML or XML markup contained within the element.

I hope this post will be helpful for you.