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

200
Vistas
I'm comparing two variables in an IF statement but I'm getting wrong results

I tried this code and when running for the first time i clicked start and i got me the result "1 is smaller than 2" whick is right but after changing the first input to 10 and clicking start again, it still showed "10 is smaller than 2". Am I doing something wrong here?

<textarea type="number" id="one">1</textarea>
<textarea type="number" id="two">2</textarea>

<a href="#" onclick="start()">Start</a>

<p id="demo"></p>

<script>
function start() {
    var numberOne = document.getElementById('one').value;
    var numberTwo = document.getElementById('two').value;
    
    if(numberOne>=numberTwo) {
        document.getElementById('demo').innerHTML = numberOne + ' is bigger than ' + numberTwo;
    }
    else {
        document.getElementById('demo').innerHTML = numberOne + ' is smaller than ' + numberTwo;
    }
}
</script>
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You are comparing strings, not numbers.

use parseInt or parseFloat to convert it to a number.

var numberOne = parseFloat(document.getElementById('one').value);
about 4 years ago · Juan Pablo Isaza Denunciar

0

Yes it is expected, input in DOM always string even if the type is number.

parse them to number first before comparing.


const intOne = parseInt(numberOne, 10);
const intTwo = parseInt(numberTwo, 10);


// compare them
if (intOne >= intTwo) {
  // do your thing
}

Edit: Update code by @Sebastian Simon suggestion

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