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>
Thus, 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 the string
s for numbers, I used the constructor Number()
.
But you could also have used the methods parseInt()
or parseFloat()
.
If possible click on [Edit] and post your code.
– Valdeir Psr
Probably what you want is not validation but to convert the values to int or float.
– Valdeir Psr
and how do I do that
– andreia