A high-contrast photograph of ducks and swans being fed from a snowy river bank in Krakow, Poland

Of the many new features introduced by HTML5, only one element was designed to be the exact opposite of a tag that already existed: <output>, the logical companion to HTML’s <input>.

Originally designed to contain the results of a form calculation, the scope of the <output> element was expanded to make it useful for many purposes, not just traditional forms. However, like <progress> and other tags, <output> depends on HTML5’s close relationship with JavaScript: without the addition of some simple scripting, the tag doesn’t have a great deal of utility.

To demonstrate the <output> element, let’s say that we want to create an online purchasing system for concert tickets in North America, with a cover price of $25 per head. All purchases will be limited to 12 tickets. The basic markup for the form would be:

<form>
	<label for="ticketcount">Number of passes</label>
	<input type="number" name="ticketcount" id="ticketcount" min="1" max="12" value="1" onchange="spinny()">
	<span id="price">@ $25 per ticket</span> =
	<output name="total" for="ticketcount price">$25</output>
</form>

Note that the <output> element contains default content, and that practices are followed, with the addition that the for attribute of the output takes all the space-delimited id values of the elements that contribute to its final value.

To update the total cost of ticket purchases, we can use a little JavaScript:

var total = document.querySelector('output[name="total"]'),
ticketcount = document.getElementById('ticketcount');
function spinny() {
	total.value = "$" + ticketcount.valueAsNumber * 25;
}

The result:

@ $25 per ticket = $25

The <output> element can also be used to display the value of a form input that otherwise lacks presentation, such as range.

<form oninput="weight.value =  shippingweight.valueAsNumber.toPrecision(3)">
	<label for="shippingweight">Shipping Weight</label>
	<input type="range" min="0" max="25" value="1.0" step="0.1" name="shippingweight" id="shippingweight">
	<output name="weight" for="shippingweight">1.0</output>kg
</form>

The result:

1.0kg

In a broader sense, the <output> element can be used to show the outcome of a user action: for example, the reported results of a form submission.  <output> is extremely versatile and easy to style: you can use any CSS on it that can be applied to any other element. Best of all, it has support in all modern browsers: there's no need for any polyfills.

Photograph by Marcin Ryczek

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.