Adding values in Javascript

Asked

Viewed 3,966 times

1

In the following code, by clicking on the input name "goalkeeper" it changes another input with the desired value. The problem is that I would like to put another field that automatically calculates the total value (goalkeeper value + technical value), but I can’t. Could someone help me?

Script

<script type="text/javascript"> 
    function alterarValor(objeto, valor) {
    document.getElementById(objeto).value = valor;
    }
</script>

Html:

<input name="goleiro" onclick="alterarValor('valor_goleiro', '5');" value="5" type="radio" id="gol" />
<input name="tecnico" onclick="alterarValor('valor_tecnico', '10');" value="10" type="radio" id="tec" />



Valor do seu goleiro: <input type="text" id="valor_goleiro" value="0" disabled /><br/>
Valor do seu Técnico: <input type="text" id="valor_tecnico" value="0" disabled /><br/>


Valor Total: <input type="text" id="valor_total" value="0" disabled /><br/>
  • Searching the internet I already got. What do I do? remove the post or I should post the solution anyway?

  • 1

    Put as an answer, will help those who go through a problem of sums similar to yours.

  • 1

    removes quotes from the number to avoid calling parseint(), saves resources

1 answer

1


The solution was simple, I just created one more function, and called the two functions in onclick. Observe:

<script>
function somar(){
    var gol = document.getElementById("valor_goleiro").value;
    var tec = document.getElementById("valor_tecnico").value;
    var soma = parseInt(gol) + parseInt(tec);
    document.getElementById("valor_total").value = soma;
}
</script>

And in the inputs, call the 2 in the onclick:

<input name="goleiro" onclick="alterarValor('valor_goleiro', '5');somar();" value="5" type="radio" id="gol" />

Like I said, simpler than I expected!

Browser other questions tagged

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