html
  1. html-output-tag

HTML <output> Tag

  • The <output> tag is a self-closing HTML tag that represents a calculated result value - usually, as a part of a calculation executed by a script.
  • It is used to provide the result value of a calculation to the user.

Syntax

The basic syntax for using the <output> tag is as follows:

<output for="id_of_evaluated_element">default_value</output>
  • for: This is an optional attribute that associates the output element with the ID of the element being evaluated. It tells the browser which control is associated with the calculated result.
  • default_value: This is an optional attribute that sets the default value of the output element.

Example

Consider the following example where an output element displays the sum of two input fields on clicking the button:

  <form>
    <label for="num1">Enter the first number:</label>
    <input type="number" id="num1" name="num1" required><br><br>

    <label for="num2">Enter the second number:</label>
    <input type="number" id="num2" name="num2" required><br><br>

    <button type="button" onclick="addNumbers()">Add</button><br><br>

    <label for="result">Result:</label>
    <output id="result">0</output>
  </form>
Try Playground

Explanation

The <output> tag is used to display the result of the addition of the two numbers in the input fields. The for attribute associates the output value with the IDs of the two input fields, and the value attribute is used to set the default value of the output tag.

When the “Add” button is clicked, JavaScript is used to calculate the sum of the two input values, which is then assigned to the value attribute of the <output> tag.

Use

The primary use of the <output> tag is to display the result of any calculation performed using JavaScript or any other scripting language. It can also be used to display the result of calculations made on the server-side.

Important Points

  • The for attribute is optional but is useful in cases when the output value corresponds to a specific input value.
  • The form element is optional, but it is recommended to group the input, output, and calculation elements together using the form element.
  • The default content of the <output> element is used as the fallback content in case the calculation is not valid, or the browser does not support the <output> tag.

Summary

The <output> tag in HTML is a self-closing tag used to display the result of a calculation using JavaScript or server-side processing. It allows you to show the calculated output value and associate it with the input field that is evaluated. The tag is a part of HTML5 and does not require any special download or installation.

Published on: