• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

166
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 3 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 3 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 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda