HTML HTML Tutorial HTML Forms HTML Graphics HTML Media HTML APIs HTML Tags



HTML Tag: output

HTML is a markup language used to create web pages. It consists of various tags that define the structure and content of a web page. One such tag is the <output> tag, which is used to display the result of a calculation or user input on a web page.

Brief Explanation of HTML Tag: Output

The <output> tag is used to display the result of a calculation or user input on a web page. It is typically used in conjunction with other HTML tags, such as <form> and <input>, to create interactive web pages.

The <output> tag has several attributes that can be used to customize its behavior. The most commonly used attributes are:

  • for: Specifies the ID of the form element that the output is associated with.
  • name: Specifies a name for the output element.
  • form: Specifies the ID of the form that the output element belongs to.

Here are some examples of how the <output> tag can be used:

Code Examples

Example 1: Displaying the Result of a Calculation

In this example, we will use the <output> tag to display the result of a calculation:

  
    <form>
      <label>Enter a number:</label>
      <input type="number" id="num1">
      <br>
      <label>Enter another number:</label>
      <input type="number" id="num2">
      <br>
      <button onclick="addNumbers()">Add Numbers</button>
      <br>
      <output name="result"></output>
    </form>

    <script>
      function addNumbers() {
        var num1 = parseInt(document.getElementById("num1").value);
        var num2 = parseInt(document.getElementById("num2").value);
        var result = num1 + num2;
        document.getElementsByName("result")[0].value = result;
      }
    </script>
  

In this example, we have created a form with two input fields and a button. When the button is clicked, the addNumbers() function is called, which adds the two numbers and sets the value of the <output> tag to the result.

Example 2: Displaying User Input

In this example, we will use the <output> tag to display user input:

  
    <form>
      <label>Enter your name:</label>
      <input type="text" id="name">
      <br>
      <button onclick="displayGreeting()">Display Greeting</button>
      <br>
      <output name="greeting"></output>
    </form>

    <script>
      function displayGreeting() {
        var name = document.getElementById("name").value;
        var greeting = "Hello, " + name + "!";
        document.getElementsByName("greeting")[0].value = greeting;
      }
    </script>
  

In this example, we have created a form with a text input field and a button. When the button is clicked, the displayGreeting() function is called, which gets the value of the input field and sets the value of the <output> tag to a greeting message.

References

Activity