Working with HTML Form Calculated Fields
This guide examines the HTML 5 calculated field element that will perform math on form element values, this includes a basic project example.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this video, we're going to talk about an interesting element called Calculated Fields that is available only in HTML5. This element is best used when you want to present some live update on the screen.

For this example, we're going to take a total value, add the cost of shipping to it, and present the final invoice value to the user.

To start with, go all the way to the top. In your <form> tag, add an attribute called input and pass a value to it. This tag will essentially keep watching if the user types in an input, and will act accordingly. In this case, we want this attribute to calculate the total cost of the invoice and the shipping cost, and we can do that with the code:

<body>
    <form action="contact_form.php" method="get" oninput="invoice.value=parseInt(total.value)+parseInt(shipping.value)">

If you find this code weird, don't worry! The idea is just to show you what this tag can do.

Now that's done, let's create the calculated field. As always, we'll start with a label and call it "Subtotal". Next, we'll create an input field of type text, and have an initial value of 0. Likewise, we'll create another label and input field with the name "shipping." The default value for this text field is 9. Then, we'll calculate the total cost, and for this, we'll use a tag called <output>. We'll give a name for the <output> tag.

So, the complete code is:

<label for="total">Subtotal:</label><br>
<input type="text" name="total" value="0" /><br>

<label for="shipping">Shipping:</label><br>
<input type="text" name="shipping" value="9" /><br>

Total for invoice: <output name="invoice" for="total tax"></output>

You can test it out on your browser. Enter any number in your shipping field, and you'll see that the final output is that value plus nine. The value of shipping can be updated as well, and the total field would reflect this change.

medium

Let's go back to the code and see how exactly how it works. If you look at the input attribute, it says invoice.value, and this invoice is what we've given as a name for the <output> tag. It's absolutely important that these names match. Similarly, we are taking the value of total field and shipping field while calculating, so the names of these fields should match with the formula we have in input.

HTML5 parses the integer value of these fields and adds them up, to give us a final value that is stored in input tag. When we use the output tag, this value is communicated to the output tag, so the final value gets displayed.

One thing to note is this element may not be supported by older browsers, typically anything below IE 9.0.

So, this is how you can calculate values dynamically in HTML.