Add values of 2 fields, click on the button and appear the result in a third field

Asked

Viewed 386 times

0

I would like to add the values informed in two fields/inputs click on the button and the answer appears in another field/input. I can’t figure out what’s missing in the code below.

<!DOCTYPE HTML>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <title>JS Examples</title>
</head>
<body>
 <input type="text" id="soma1" maxlength="5"><br><br>
 <input type="text" id="soma2" maxlength="5"><br><br>

 <button id="btn">Resultado</button><br><br>

 <input type="text" id="resultado" maxlength="5">
</body>
</html>
<script type="text/javascript">

 var soma1 = document.getElementById('soma1');  
 var soma2 = document.getElementById('soma2');
 var btn = document.getElementById('btn');
 var result = document.getElementById('resultado');

 soma1 = parseInt(soma1.value);
 soma2 = parseInt(soma2.value);


 btn.addEventListener('click', function(){
   somatotal();
 });    

 function somatotal(){
  var soma = soma1 + soma2;
    document.getElementById('resultado').value = soma;  
 }

  </script>

  • 1

    See help: https://answall.com/questions/173458/substr-ancora-por-bot%C3%A3o-em-formul%C3%A1rio-com-c%C3%A1lculo-pelo-javascript

  • In the answer of this question I passed you have an important information on conversion of value reported in imput.

  • Thanks for the tip Laércio!

1 answer

3


Your problem is that:

At the beginning of the application the following code is executed:

soma1 = parseInt(soma1.value);
soma2 = parseInt(soma2.value);

Assigning the value of parseInt(vazio) to the variavies. This value is not changed after typing in the field.

One solution is to take this value again whenever the button is clicked:

 var soma1 = document.getElementById('soma1');  
 var soma2 = document.getElementById('soma2');
 var btn = document.getElementById('btn');
 var result = document.getElementById('resultado');




 btn.addEventListener('click', function(){
   somatotal();
 });    

 function somatotal(){
  var soma1Val = parseInt(soma1.value);
  var soma2Val = parseInt(soma2.value);
  var soma = soma1Val + soma2Val;
    document.getElementById('resultado').value = soma;  
 }
<!DOCTYPE HTML>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <title>JS Examples</title>
</head>
<body>
 <input type="text" id="soma1" maxlength="5"><br><br>
 <input type="text" id="soma2" maxlength="5"><br><br>

 <button id="btn">Resultado</button><br><br>

 <input type="text" id="resultado" maxlength="5">
</body>
</html>

  • Edson thank you! your explanation made everything clear! abç

Browser other questions tagged

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