Jonathan Foster Jonathan Foster - 1 year ago 65
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?


Enter 2 numbers to see which one is highest.
<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.


.inputs {
float : left;

#secondnumber {
clear: both;

#button {
clear: left;

p {
clear: both;


function myfunction(num1, num2) {
if (num1 > num2) {
"The Higher number is " + num1 + ", which was the first value.";
} else {
"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);


Thank you very much.

Answer Source

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

if (Number(num1) > Number(num2)) {


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download