It is often required to make an online form that can calculate the totals. Here is a simple HTML calculation form It is structured like an invoice form so that you can copy and adapt. Note that “simple” is meant to be taken as easy to understand. So I have avoided any temptation to make the smallest code. Also, the code uses some jQuery to do the calculation
Here is a sample calculation form. Try entering the quantity field. It will automatically update the totals. Note that the item price is calculated and can’t be changed.
See the Pen Simple HTML calculation form on CodePen.
HTML code (row)
<div class="row">
<div class="col-6">
1. Powdered white sugar (cups)
</div>
<div class="col-3">
<input type="number" value="0" class="qty" id="qty_sugar" />
</div>
<div class="col-2">
<input type="number" readonly value="0" id="price_sugar" />
</div>
</div>
The HTML code above creates a row in the invoice form. Notice the id attributes of the quantity and unit price fields.
The rest of the rows are added similarly Only the ID of the fields are changed
Let us now see the arithmetic behind this calculation: The user can enter only the quantity of the items. We calculate the price of each item by multiplying:
qty × unit_price
All that we need to do is to write JavaScript code that calculates the total. Note that this code uses a Javascript library called jQuery. jQuery makes this code a bit easier to understand
function calculateTotal()
{
let unit_price={
sugar: 22,
butter: 12,
eggs: 2,
vanilla:43
};
let item_price={}
item_price.sugar = ($("#qty_sugar").val() * unit_price.sugar )
$("#price_sugar").val(item_price.sugar);
...
...
}
This code $("#qty_sugar").val()
gets the value of the field with ID qty_sugar
The codde $("#qty_sugar").val() * unit_price.sugar
means to multiply the value of qty_sugar with the sugar price (initialized above ). The symbol * is used for multiplication in Javascript.
This line of code: $("#price_sugar").val(item_price.sugar);
sets the result of the multiplication to the field price_sugar
.
The quantity * price value is calculated similarly for the rest of the fields.
Then we just add all the multiplication results to find the total.
let total = item_price.sugar + item_price.butter + item_price.eggs + item_price.vanilla;
Finally we set the value of the “total” using this code:
$("#total_value").text(total);
But, how does the calculation run every time you edit the quantity? For that, we have to handle the “events”
Event Handling
The code below hooks on to the change and keyboard events for all the fields with the class attribute qty
Then it runs the calculation function. So for every update, the form calculates the total and displays to you!
$(function()
{
$(".qty").on("change keyup",calculateTotal)
})
Customizing
To add your items, search for one of the items in the current form (for example “sugar” ) then try changing it. Once you have made the changes, you will get an idea of how the changes affect the working of the form.