<output> elementThe <output> element represents the result of a calculation or the result of an action performed by the user. It is the place where the page says, "after these inputs or this action, this is the result."
A simple example is a form that adds two numbers. The number fields are the inputs, and the <output> element is the answer. This is clearer than using a plain <span>, because the HTML itself says that the text is a produced result.
The for attribute can list the id values of the controls that influenced the result. Separate the IDs with spaces. This records the relationship; it does not perform a calculation or automatically update the result.
The form attribute can associate the output with a form, even if the element is not physically inside that form. The name attribute gives the output a name in the form's element collection, but the output's value is not submitted like a normal input value.
This element should not be confused with <samp>. The <samp> element quotes output from another program or system. The <output> element is for output produced by the current page, form, or application.
JavaScript can update the result through the output's value property. The example uses two labelled <input> controls and recalculates when either changes. If either field is empty or invalid, it asks for two numbers rather than treating a missing value as zero.
The controls and result have separate <label> elements. A label's for identifies the control it names; the output's own for lists the inputs involved in the calculation. The script shown below supplies the behaviour, and the calculation stays on this page.
Attributes: for, form, name, GLOBALS.
Typical layout: <p><label for="pf-demo-a">First number</label><br> <input id="pf-demo-a" type="number" step="any" value="3" required></p> <p><label for="pf-demo-b">Second number</label><br> <input id="pf-demo-b" type="number" step="any" value="5" required></p> <p><label for="pf-demo-total">Total</label>: <output id="pf-demo-total" for="pf-demo-a pf-demo-b">8</output></p>
Visual representation:
:
JavaScript for this example:
const firstNumber = document.getElementById('pf-demo-a');
const secondNumber = document.getElementById('pf-demo-b');
const total = document.getElementById('pf-demo-total');
function updateTotal() {
const a = firstNumber.valueAsNumber;
const b = secondNumber.valueAsNumber;
if (!firstNumber.validity.valid || !secondNumber.validity.valid
|| !Number.isFinite(a) || !Number.isFinite(b)) {
total.value = 'Enter two numbers.';
return;
}
const sum = a + b;
total.value = Number.isFinite(sum) ? String(sum) : 'Result is too large.';
}
firstNumber.addEventListener('input', updateTotal);
secondNumber.addEventListener('input', updateTotal);
updateTotal();