1

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.

RightSaidFred
  • 11,209
  • 35
  • 35
CallumVass
  • 11,288
  • 26
  • 84
  • 154

2 Answers2

6

You're comparing strings. Convert them to numbers first.

var qty = Number( $(this).val() );
var stock = Number( $('#StockLvl').val() );

or

var qty = +$(this).val();
var stock = +$('#StockLvl').val();

or

This way will be safest in your case.

var qty = parseInt( $(this).val(), 10 );
var stock = parseInt( $('#StockLvl').val(), 10 );
RightSaidFred
  • 11,209
  • 35
  • 35
0

You are dealing with string comparison not number. Put a parseInt around the values and you will get the expected result.

Mike
  • 364
  • 1
  • 9