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

HTML

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

Javascript

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.