Form Controls in HTML: Outputting Calculation Result

<output>… <output>

The <output> element is used to display the result of a calculation. However, the use of JavaScript is necessary to use it. To address this, HTML5 also includes the valueAsNumber property of JavaScript, which returns a string as a number and is relatively straightforward to use. Table 5.16 lists the attributes supported by the element. Figure 5.51 shows how the element is used, and Figure 5.52 depicts the result.

The example shows two numbers being added together, as each is inputted by the user. The number-input type (discussed earlier) is used to collect each number, and the <output> element displays the content of the value of the name attribute (i.e., “sum”). The oninput event attribute on the <form> element takes care of the addition of the numbers and the placing of the result in “sum.” The equation says to take the values stored in “a” and “b,” use the valueAsNumber function to change each to a number, add the numbers together, and then make the result the value of the element named “sum” Notice the dot convention. This is the convention used in object- oriented programming to specify to access what is stored in a variable or apply a function to it.

Source: Sklar David (2016), HTML: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *