Error converting integer in JS from an HTML input

Asked

Viewed 45 times

2

Good afternoon friends, today I started my journey in JS learning and in the course I’m doing was passing an exercise that I tried in another way that the teacher taught and ended up going wrong. I already managed to do it the way it worked. But I still don’t know why it went wrong in my modification. follow the code:

<body>
<h1>Somando 2 numeros</h1>
<input type="number" id="num1"> +
<input type="number" id="num2">
<input type="button" value="Somar" onclick="somar()">
<div id="soma">Resultado</div>
<script>
function somar(){
    var n1 = Number(window.document.getElementById('num1'))
    var n2 = Number(window.document.getElementById('num2'))
    var res = window.document.getElementById('soma')
    var s = n1 + n2
    res.innerText = (s)
}

</script>

Thank you since

Mariops

1 answer

3


You added the elements <input> obtained by document.getElementById() what was missing was adding up the values of the attributes value of each <input>.

<body>
  <h1>Somando 2 numeros</h1>
  <input type="number" id="num1"> +
  <input type="number" id="num2">
  <input type="button" value="Somar" onclick="somar()">
  <div id="soma">Resultado</div>
  <script>
    function somar() {
      var n1 = Number(window.document.getElementById('num1').value) //note o .value que não tinha antes
      var n2 = Number(window.document.getElementById('num2').value)
      var res = window.document.getElementById('soma')
      var s = n1 + n2
      res.innerText = (s)
    }
  </script>

Browser other questions tagged

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