Jonathan Foster Jonathan Foster - 4 months ago 7
CSS Question

Why does this javascript function stop working?

What I have here is I think a simple comparison application that takes 2 numbers, sees which one is bigger and then changes the inner HTML of a paragraph accordingly. When I run it it seems to be working ok but as I start plugging new numbers in around the 3rd or 4th time it stops working and starts saying that the lower number is higher. It seems to be random when this happens. Could anyone explain to me why it's happening?

Html:

<p>
Enter 2 numbers to see which one is highest.
</p>
<input type="text" id="firstnumber" class="inputs" class="clearme"/>
<input type="text" id="secondnumber" class="inputs"/>
<input type="button" class="inputs" value="submit" id="button"/>
<p id ="message" style="color: blue;">
Answer appears here.
</p>


Css:

.inputs {
float : left;
}

#secondnumber {
clear: both;
}

#button {
clear: left;
}

p {
clear: both;
}


Javascript:

function myfunction(num1, num2) {
if (num1 > num2) {
document.getElementById("message").innerHTML=
"The Higher number is " + num1 + ", which was the first value.";
} else {
document.getElementById("message").innerHTML=
"The Higher number is " + num2 + ", which was the second value.";
}
}

document.getElementById('button').onclick = function(){
var x = document.getElementById("firstnumber").value;
var y = document.getElementById("secondnumber").value;
myfunction(x, y);
console.log(x);
console.log(y);
}


jsfiddle:
https://jsfiddle.net/wxzLbnu1/1/

Thank you very much.

Answer

You need to convert the numbers before you compare them. You can accomplish this by using the Number() function.

if (Number(num1) > Number(num2)) {
  //...
};

JSFiddle