You weren’t far away, you’re missing two things.
When you want to access the value of a input
, and even when you want to change its value you have to use the property .value
. In your first input you gave to x
the element itself, not its value. In the second you are trying to rewrite the .innerHTML
that the input
no. Uses .value
both of us.
The other thing that failed is because the .value
returns a String, or a text. So you notice that "10"
is not the same as 10
. The first is text (String), the second a number (Number). To convert you can use the parseInt(numero, radix)
or the parseFloat(numero)
.
With these changes would have worked by now. But I suggest you use the onkeyup
. The keypress
is fired before of the input receiving the new number, and so (as in the link above) it will calculate before the new number is there. Changes to keyup
for him to make the account already with the right value.
So for it to work you can use it like this:
function tenta() {
var x = document.getElementById('ciclo').value;
document.getElementById('lol').value = parseFloat(x) + 3;
}
<input type="text" name="ciclo" id="ciclo" maxlength="4" onkeyup="tenta()">
<input type="text" readonly id="lol">
I think that
Math.round()
is not semantically correct. It works because it converts the string into a number, in the same way thattypeof ("5" * 1)
gives a"number"
. The methodsparseInt
orparseFloat
is what is semantic for converting strings into numbers.– Sergio