Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

236
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda