Home > Software engineering >  Condition if else shows me the results backwards. What's going on?
Condition if else shows me the results backwards. What's going on?

Time:06-28

I have made a simple if else condition where it should show which is the greater number of the two inputs entered, but it shows me the opposite value than expected. What's going on? Thanks in advance!

HTML:

 <input type= "text" id="texto">
 <input type= "text" id="texto2">
 <button type="submit" id="enviar">Enviar</button>

JS:

const texto = document.getElementById('texto');
const texto2 = document.getElementById('texto2');
const send = document.getElementById('send');
send.addEventListener('click', mayorque)


function mayorque() {

if (texto > texto2){
    
    alert('Input 1 is greater than input 2')
} else {
    alert('Input 2 is greater than input 1')
}

    
}

CodePudding user response:

A few problems.

When you set the variable texto on load, it is grabbing the value of the input on load. You will need to get the value in the function.

Using something like parseFloat will convert the value to a numeric value. Float will allow for decimal points.

let texto = document.getElementById('texto');
let texto2 = document.getElementById('texto2');
const send = document.getElementById('send');
send.addEventListener('click', mayorque)


function mayorque() {
  texto = parseFloat(texto.value);
  texto2 = parseFloat(texto2.value);
  if (texto > texto2) {

    alert('Input 1 is greater than input 2')
  } else {
    alert('Input 2 is greater than input 1')
  }


}
<input type="text" id="texto">
<input type="text" id="texto2">
<button type="submit" id="send">Enviar</button>

  • Related