Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
Parse float not working as expected in JS

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>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)
}
about 4 years ago · Juan Pablo Isaza Report

0

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)
    }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!