开发者

Comparing the values of two text-fields using jQuery

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()开发者_JS百科;

    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.


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!");
    }
});


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜