0

Consider the following HTML tables:


<table id="myTable1">
    <tr><td><input type="text" id="quantity1" name="quantity1" /></td></tr>
    <tr><td><input type="text" id="quantity2" name="quantity2" /></td></tr>
</table>

<table id="myTable2">
    <tr><td>
        <input type="text" id="total_quantity" name="total_quantity" />
        <input type="text" id="total_quantity_max" name="total_quantity_max" />
    </td></tr>
</table>


  • total_quantity_max contains a constant integer value, whereas
  • total_quantity will hold the SUM value based on the values of the quantity fields
  • value of total_quantity is updated everytime keyup is triggered on the quantity fields


What I'm trying to do is to alert the user the instant that the value in total_quantity becomes greater than the value in total_quantity_max.

At first I thought this could be achieved with something like:


$('#myTable1 input[id^=quantity]').live('keyup',function() {
    var n = $("#myTable2 #total_quantity").val();
    var m = $("#myTable2 #total_quantity_max").val();

    if(n > m) {
        alert("Alert!");
    }
});


However I'm encountering problems using the above code such as; the alert gets triggered even though the value in total_quantity clear is not > total_quantity_max.

2
  • 1
    You're comparing strings, not actual numbers.. Commented Oct 12, 2011 at 13:43
  • what are the actual values you get for n and m Commented Oct 12, 2011 at 13:44

2 Answers 2

2

It's because the comparison is done with string and not number. Try to use parseFloat.

$('#myTable1 input[id^=quantity]').live('keyup',function() {
    var n = $("#myTable2 #total_quantity").val();
    var m = $("#myTable2 #total_quantity_max").val();

    if(parseFloat(n) > parseFloat(m)) {
        alert("Alert!");
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Ah Strings. I always assumed those are automatically read as integers. Thanks the code's working now!
2

Use parseInt - val will return a string and strings have different comparison rules from integers.

if(parseInt(n, 10) > parseInt(m, 10)) {
    alert("Alert!");
}

3 Comments

Always use parseInt(n,10). If n were 09 and m were 04, your if statement would fail.
Nah, he should use TryParse, if his string contains anything else than a number it would fail anyway
@Rob You mean this C# function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.