How to create a useful calculator widget in plain HTML quickly: sample code and live demo

HTML calculation Javascript calculation age calculation

While HTML is primarily used for creating the structure and content of a web page, HTML can also be used to create interactive features such as an age calculator. It requires a bit of some script; but is easy to integrate. An age calculator is a useful tool for websites that deal with date-related content or services. In this tutorial, we will guide you through the steps of coding a simple age calculator in HTML.

Create the HTML form

Add input fields for the user to enter their birthdate. You can use HTML input type=“date” field to create the birth date input field.

<div class="container mt-5">
    <div><label for="birth_date">Birth Date: </label>
      <input type="date" id="birth_date" name="birth_date" />
    <div id="age" style="padding-top:2em;">
      Age: <span r-calc="calculateAge(birth_date)"></span>

With that simple block of HTML code, you can create an age calculator.

The trick that simplifies the code is that we use a calculation utility library called NittiJS. Once you have NittiJS added to the page, just add an attribute r-calc with the formula to calculate the results and you have a live calculation form ready!

NittiJs includes some utility functions also that helps us in this age calculator. calculateAge function calculates the age from a given date input field.

See a demo of the age calculator here:

See the Pen Calculate age HTML Code

Another simple calculator widget using NittiJS

Here is another simple HTML calculation widget using NittiJS. This time we have a Tip calculator

<div class="container mt-3" style="max-width: 340px;">
<h1>Tip Calculator</h1>
    <div class="mb-3">
    <label class="form-label" for="billTotal">Bill Total:</label>
    <input class="form-control" type="number" id="billTotal" name="billTotal">
    <div class="mb-3">
    <label for="tipPercentage" class="form-label">Tip Percentage:</label>
    <select class="form-select" id="tipPercentage" name="tipPercentage">
      <option r-value="0.10">10%</option>
      <option r-value="0.15">15%</option>
      <option r-value="0.20">20%</option>
      <option r-value="0.25">25%</option>

        Tip: <span r-calc="billTotal * tipPercentage" r-format="currency|usd"></span>


Note that the formula is directly given in the r-calc attribute. We have another attribute r-format that tells the calculator to format the value as currency.

Another important point to note is that we have an r-value attribute in the options to map from the selection to corresponding numeric value to be used in the calculation. This makes the calculation so simple.

See more calculation forms here

See Also