Home > OS >  Parse float not working as expected in JS
Parse float not working as expected in JS

Time:03-19

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>

CodePudding user response:

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)
}

CodePudding user response:

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)
    }
  • Related