Strange error when adding [duplicate]

1

I have 2 input fields and I need to add the value of their contents when typing, but I noticed that when I type the first value in the first input it appears NaN only when I type something in the second input, it starts to add, so if I have 5 inputs, I would have to keep all of them to have a sum.

I want to add as I enter the values in the input, without having to fill all, if I fill some already makes the sum,

My Code:

<html>
<head>
<title></title>
<script type="text/javascript">
function somar()
{
	var campo_1 = document.getElementById("campo_1").value;
	var campo_2 = document.getElementById("campo_2").value;
    var campo_3 = document.getElementById("campo_3").value;
    var campo_4 = document.getElementById("campo_4").value;
    var campo_5 = document.getElementById("campo_5").value;

	var somar = parseInt(campo_1) + parseInt(campo_2) + parseInt(campo_3) + parseInt(campo_4) + parseInt(campo_5);

	console.log(somar);

}
</script>
<body>
<input id="campo_1" onkeydown="somar();" type="text"></input>
<input id="campo_2" onkeydown="somar();" type="text"></input>
<input id="campo_3" onkeydown="somar();" type="text"></input>
<input id="campo_4" onkeydown="somar();" type="text"></input>
<input id="campo_5" onkeydown="somar();" type="text"></input>
</body>
</html>
    
asked by anonymous 14.11.2016 / 21:21

2 answers

1

This should work:

function somar()
{
    var campo_1 = document.getElementById("campo_1").value || 0;
    var campo_2 = document.getElementById("campo_2").value || 0;
    var campo_3 = document.getElementById("campo_3").value || 0;
    var campo_4 = document.getElementById("campo_4").value || 0;
    var campo_5 = document.getElementById("campo_5").value || 0;

    var somar = parseInt(campo_1) + parseInt(campo_2) + parseInt(campo_3) + parseInt(campo_4) + parseInt(campo_5);

    console.log(somar);

}
    
14.11.2016 / 21:30
0

See if you can adapt this function to what you want.

    function somar()
    {
    total = 0; //variavel começa zerada
//funcao each que varre todos os elementos do tipo que voce quer
    $("input").each(function( index ) { 
        if ($(this).value != null) //se o valor for diferente de nulo
        {
        total += $(this).value; //adiciona valor à total
        }
console.log(total);
    });
    
14.11.2016 / 21:24