Strange error when adding

Asked

Viewed 58 times

1

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

I want it to add up as I enter the values in the input, without needing to fill them all, if I fill in 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>

2 answers

1


That 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);

}
  • That’s what I’ve been looking for, thank you

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);
    });
  • But the value can not appear in the field, has to be blank, as I do friend ?

  • I changed the code, see now

  • This if is not very practical, because I have more than 200 fields on the screen, rsss. There would be a simpler way ?

  • changed again, try using the example above for what Voce wants.

  • Thanks for the tip.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.