The <output> element
Published on
Pretty much everyone knows about the <input>
element, but we don’t hear about <output>
nearly as often.
The <output>
element is designed for showing the results of calculations and other types of user interactions.
It’s perfect for things like calculators, or in form where you’re adding several fields together, as well as other places where you want to provide users with real-time feedback based on their inputs.
Here’s a very simple calculator as an example:
<form oninput="result.value = parseInt(a.value) + parseInt(b.value)">
<input type="number" name="a" value="50" /> +
<input type="number" name="b" value="25" /> =
<output name="result" for="a b">75</output>
</form>
Which would give you this:
Attributes
The for
attribute is used to indicate the elements that contributed values to the output,using a space-separated list the elements’ ids.
<output name="result" for="a b">75</output>
You can also use the form
attribute to associate the output to a specific form, even if it’s not nested inside it:
<form id="calculator">
<input type="number" name="a" value="10" />
<input type="number" name="b" value="5" />
</form>
<!-- Somewhere else-->
<output form="calculator" name="result" for="a b">15</output>
If the <output>
is nested in a <form>
you don’t need to include this, the browser will use it’s ancestor form element. However, if the output is inside a form, you can still link it to a different form using the form
attribute if needed.
Accessibility
The <output>
element has an implicit role="status"
, which is a type live region. This role gives it an implicit aria-live="polite"
, which means that they’ll announce the results without users needing to switch focus to the output, but only when the user is is idle.
Important to remember
The output element’s name and content are not submitted when the form is submitted. It’s purely for display purposes, so if you need the calculated value in your form submission, you’ll need a hidden input field as well.