0

I trying to alert sum of 2 numbers from inputs but problem is that i cannot convert it into number type. Instead of this i getting NaN. Snippet:

var ipt1 = document.getElementById("w1").value;
var ipt2 = document.getElementById("w2").value;

function add(){
  let l1 = parseInt(ipt1)
  let l2 = parseInt(ipt2)

  alert( l1 + l2 )
}
<body>
    <input type="" id="w1"><br>
    <input type="" id="w2"><br>

    <input type="submit" value="dodaj" onclick="add()">
</body>
1
  • You should grab the values inside the add function. You are now grabbing the values while the inputs are empty. Commented Mar 18, 2022 at 22:58

2 Answers 2

2

The problem is that the values are stored into the variables while the input is empty.

You should grab the values after the user has entered the values and clicked add():

var ipt1 = document.getElementById("w1").value; // Input is empty at this point
var ipt2 = document.getElementById("w2").value; // Input is empty at this point

function add(){
  let l1 = parseInt(ipt1); // You are parsing an empty value
  let l2 = parseInt(ipt2); // Same here...
  alert(l1+l2)
}

What you should do:

const ipt1 = document.getElementById("w1");
const ipt2 = document.getElementById("w2");

function add(){
  const l1 = parseInt(ipt1.value); 
  const l2 = parseInt(ipt2.value); 
  alert(l1+l2)
}
Sign up to request clarification or add additional context in comments.

Comments

1

What you are doing is you are extracting the values of the input fields before typing them in input field i.e ipt1 and ipt2 will give "" as their value was extracted as the page was loaded. Instead try extracting the value at the time of clicking the submit button.

Try this

    function add(){
    var ipt1 = document.getElementById("w1").value
    var ipt2 = document.getElementById("w2").value
    let l1 = parseInt(ipt1)
    let l2 = parseInt(ipt2)
    console.log(ipt1,l1)

    alert(l1+l2)
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.