[javascript] javascript if number greater than number

I have this javascript function to validate if a number is greater than another number

function validateForm() {
    var x = document.forms["frmOrder"]["txtTotal"].value;
    var y = document.forms["frmOrder"]["totalpoints"].value;

    if (x > y) {
        alert("Sorry, you don't have enough points");
        return false;
    }
}

It's not working for some reason.

If I do alert(x) I get 1300, and alert(y) gives 999

This works....

function validateForm() {
    var x = 1300;
    var y = 999;

    if (x > y) {
        alert("Sorry, you don't have enough points");
        return false;
    }
}

This question is related to javascript forms

The answer is


You should convert them to number before compare.

Try:

if (+x > +y) {
  //...
}

or

if (Number(x) > Number(y)) {
  // ...
}

Note: parseFloat and pareseInt(for compare integer, and you need to specify the radix) will give you NaN for an empty string, compare with NaN will always be false, If you don't want to treat empty string be 0, then you could use them.


Do this.

var x=parseInt(document.forms["frmOrder"]["txtTotal"].value);
var y=parseInt(document.forms["frmOrder"]["totalpoints"].value);

You're comparing strings. JavaScript compares the ASCII code for each character of the string.

To see why you get false, look at the charCodes:

"1300".charCodeAt(0);
49
"999".charCodeAt(0);
57

The comparison is false because, when comparing the strings, the character codes for 1 is not greater than that of 9.

The fix is to treat the strings as numbers. You can use a number of methods:

parseInt(string, radix)
parseInt("1300", 10);
> 1300 - notice the lack of quotes


+"1300"
> 1300


Number("1300")
> 1300

You can "cast" to number using the Number constructor..

var number = new Number("8"); // 8 number

You can also call parseInt builtin function:

var number = parseInt("153"); // 153 number