w3resource

HTML5: How to define the result of a calculation?

Go to Exercise page

Solution:

HTML Code:

<!DOCTYPE html><!-- Declaration of the document type as HTML -->
<html>
<head>
<meta charset="utf-8"><!-- Meta tag specifying character encoding -->
<title> How to define the result of a calculation</title><!-- Title of the HTML document -->
</head>
<body>
<form <!-- Start of form element -->
oninput="w3resource.value=parseInt <!-- JavaScript code to execute when input changes -->
(input.value)+parseInt                 <!-- Parse input value as integer -->
(output.value)">0                      <!-- Initial value -->
<input type="range" id="input"         <!-- Input field for range selection -->
value="100">100                        <!-- Default range value -->
+<input type="number" id="output"      <!-- Input field for number -->
value="10"><!-- Default number value -->
=<output name="w3resource"             <!-- Output field for displaying result -->
for="input output"></output><!-- Associated inputs for the output -->
</form><!-- End of form element -->
</body>
</html>

Explanation:

  • This HTML code creates a simple form that allows users to input a number and select a range.
  • The sum of the number input and the range selection is displayed in real-time.
  • Here's the breakdown:
    • The form starts with a declaration and contains various input elements.
    • The JavaScript code inside the oninput attribute calculates the sum of the range input and the number input.
    • The parseInt() function is used to convert the input values from strings to integers for proper addition.
    • The input element with type range allows users to select a value within a specified range.
    • The input element with type number allows users to input a numeric value.
    • The result of the calculation is displayed in the <output> element with the name w3resource.
    • Comments are added before each line of code to explain its purpose.

Live Demo:

See the Pen output-answer by w3resource (@w3resource) on CodePen.


See the solution in the browser

Supported browser

Firefox logo Chrome logo Opera logo Safari logo Internet Explorer logo
Yes Yes Yes Yes Yes

Go to Exercise page

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.