Use-Cases of this tutorial
- Know how to semantically show the output or result of some calculation performed in a HTML page.
- Know about the <output> HTML tag.
If <input> tag in a HTML form represents input data, then <output> tag represents the output data of the form.
The <output> tag is the standard HTML element in which the result of any user action or calculation performed can be shown. The result can be inserted inside <output> using Javascript.
Just like the <input> tag is the standard way of accepting input from the user, <output> tag is the standard way to show a result (using the input) to the user.
<form id="sample-form">
<input type="text" name="first_name" id="f_name" />
<input type="text" name="last_name" id="l_name" />
<button>Calculate</button>
<!-- result from the input can be shown here using Javascript -->
<output name="result" id="combined" for="f_name l_name"></output>
</form>
document.querySelector("#sample-form").addEventListener('submit', function(e) {
document.querySelector("#combined").value = document.querySelector("#f_name").value + ' ' + document.querySelector("#l_name").value;
e.preventDefault();
});
Why <output> Tag ?
Obviously the result of any calculation can be inserted inside any HTML element, for example a <div> or a <span>.
However <output> is the semantic way of representing this. Automated machines & scripts can read this tag, and understand that this represents an output of some sort. They may use this information in some way.
Special Attributes of the <output> Tag
The <output> tag can have some special attributes :
- for : Represents the elements which were involved in the output shown. It needs to be a space separated list of IDs of the elements involved.
- form : Represents the ID of the form whose output will be shown.
- name : Represents the name of the tag.
- value : Represents the value of the output. This value is typically generated using Javascript.