having trouble with user-input addition

Viewed 24

javascript newbie here. I was trying to add 2 numbers via user input but the code returns a NaN warning in the console. I know other methods to do this but i wanted to it with the ES6 Features.


//HTML

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form>
        <input type="number" name="num1" id="num1">
        <input type="number" name="num2" id="num2">
        <button type="submit" value="+">+</button>
        <input type="number" name="num3" id="num3">
    </form>
    <script src="calculator.js"></script>
</body>
</html>


//JAVASCRIPT
const num1 = parseInt(document.querySelector('#num1').value);
const num2 = parseInt(document.querySelector('#num2').value);
const num3 =Number(document.querySelector('#num3').value);
const form = document.querySelector('form');


form.addEventListener('submit', e =>{
    e.preventDefault();

    const c = num1 + num2;
    form.num3.value = c;
});
1 Answers

This happens because

const num1 = parseInt(document.querySelector('#num1').value);
const num2 = parseInt(document.querySelector('#num2').value);

These variable are declared outside the submit method and initially they are set to NaN as input fields are empty at start and parseInt('') returns NaN. To resolve this you will simply need to call them inside form submit method, so that on every form submit call you will get the latest values for the input fields like:

const form = document.querySelector('form');

form.addEventListener('submit', e => {
  e.preventDefault();
  const num1 = parseInt(document.querySelector('#num1').value);
  const num2 = parseInt(document.querySelector('#num2').value);
  const c = num1 + num2;
  form.num3.value = c;
});
input {padding: 4px 8px; font-size: 1.5rem;}
<form>
  <input id="num1" type="number" min="0" /><br>
  <input id="num2" type="number" min="0" /><br>
  <input id="num3" type="number" readonly disabled/><br>
  <button>Submit</button>
</form>

Related