I’m experiencing a strange JavaScript/jQuery math bug when trying to determine whether one value is greater than another.
Here is a link, using jsFiddle, to my code: http://jsfiddle.net/qxeTj/
$("#Quantity").live("focusout", function() {
var qty = +$(this).val();
var stock = +$('#StockLvl').val();
if (qty > stock) {
$('#Result').html("<p>Quantity: " + qty + "</p><p>Stock: " + stock + "</p>" + "<p>Not Enough Stock.</p>");
}
else if (stock > qty || stock == qty) {
$('#Result').html("<p>Quantity: " + qty + "</p><p>Stock: " + stock + "</p>" + "<p>Enough Stock.</p>");
}
});
Example of problem:
When I focus out of the input field, if it has a value of 1 or 2, it works fine. It even works if I have a value of 3, 4, 5, 6, 7, 8, 9.
But the problem is then when I use values from 10-19 or 100-199 or 1000-1999 and so forth. It say’s it has enough stock when it shouldn’t.
You’re comparing strings. Convert them to numbers first.
or
or
This way will be safest in your case.