By default, all input values come in as string
, see:
document.getElementById('check').addEventListener('click', function() {
var field = document.getElementById('input');
// Mostra o valor e em seguida o tipo:
alert(field.value);
alert(typeof field.value);
});
<input id="input" type="number" value="44" />
<button id="check">Clique</button>
In this way, we need to transform the value of the field into a number.
var numberInString = '20';
var number = Number(numberInString);
console.log(typeof number); // number
So, I think what you need is:
document.getElementById('calc-sum').addEventListener('click', function() {
var num1 = document.getElementById('num-1');
var num2 = document.getElementById('num-2');
// Transformar os valores em números:
num1 = Number(num1.value);
num2 = Number(num2.value);
// Calcular a soma:
var sum = num1 + num2;
// Mostrar a soma:
document.getElementById('sum').innerText = 'A soma é: ' + sum;
});
<label>Valor 01: </label>
<input id="num-1" type="number" />
<br>
<label>Valor 01: </label>
<input id="num-2" type="number" />
<br><br>
<input type="button" id="calc-sum" value="Calcular soma">
<br><br>
<div id="sum"></div>
Note:
To convert string
s to numbers, I used the Number()
constructor.
But you could also have used the methods parseInt()
or parseFloat()
.