Output and form events
Show calculations with <output> and the form attribute.
Output and the for attribute
The <output> tag shows the result of a calculation. You have seen it before; now we pair it with two new attributes.
The for attribute tells the output which inputs feed it. Its value is a space-separated list of ids: <output for="a b">. This says the output follows the inputs with id="a" and id="b".
The browser can update the output automatically when the watched inputs change; it grows stronger still when paired with the form attribute.
Outer linking with the form attribute
The form attribute links an input or output to a form even when it sits outside that form. Normally an input belongs to the form that wraps it. But sometimes layout pushes an input outside.
Example: <form id="calc">...</form> and later <input type="number" form="calc">. This input is included in the form despite sitting outside.
An output can also link to a form with the form attribute; this way a result can be displayed from anywhere on the page.
Exercise Write a calculator form
Add a <form id="calc"> inside body. Inside it put an <input type="number" id="a" name="a"> and an <output for="a b" name="result"></output>. Then OUTSIDE the form add an <input type="number" id="b" name="b" form="calc">. This input must link to the form through the form="calc" attribute.
Show example solution
<body>
<form id="calc">
<label for="a">Number 1</label>
<input type="number" id="a" name="a">
<output for="a b" name="result"></output>
</form>
<label for="b">Number 2</label>
<input type="number" id="b" name="b" form="calc">
</body>
Test yourself
-
What is the core purpose of <output>?
- Show the result of a calculation
- Upload a file
- Pick a colour
- Build a menu
Show answer
Show the result of a calculation — Correct. output shows the result of a calculation.
-
Add a for attribute to the output
<output for="____" name="result"></output>Show answer
<output for="a b" name="result"></output> -
Match each attribute to its role
- for (output)
- Watched inputs
- form
- Outer form link
- id
- Unique identity
- name
- Form data name