Use the HTML5 <output>
Tag. It's designed for capturing form calculation results.
<form oninput="totalScore.value = (+num1.value)+(+num2.value)+(+num3.value);">
<input type="number" id="num1" />+
<input type="number" id="num2" />+
<input type="number" id="num3" />=
<output name="totalScore" for="num1 num2 num3"></output>
</form>
Here's a breakdown of what's happening:
Since the input is a string, we want to coerce it into a number using
+someString
We specify the list of input IDs of fields that go into the calculation. Typically, this is used so that we don't get
NaN
result in case one of the input fields is empty. But since we're coercing the input into a number, an empty string is converted to 0. Hence, it's not necessary, but good to have for clarity (especially if the calculations get more complex).Note that we don't include
name
attributes for the number inputs. This is to prevent them from getting submitted. We're only concerned about the result.
Also, here's a list of browsers that currently support output
.