Reputation: 33
I'm trying to use jQuery to compare two values in an html table, and alert the user if quantity > inventory.
I want to select values in the current row :
$('.item_quantity').change(function(){
var $this=$(this);
var quantity=$this.val();
// var inventory=$this.next('.item_inventory, td').text();
var inventory=$(this).next('td, .item_inventory').text();
console.log('quantity: ', quantity, 'inventory: ', inventory);
if (quantity > inventory) {
alert('Your order quantity ' + quantity + ' is greater than ' + inventory + ' inventory');
}
});
});
<table >
<tr>
<td><form method=""><input class="item_quantity" type="text" data-prodid="249" value=""/></form></td>
<td class="item_inventory">10</td>
<td>Product 1</td>
</tr>
<tr>
<td><form method=""><input class="item_quantity" type="text" data-prodid="2" value=""/></form></td>
<td class="item_inventory">7</td>
<td>Product 2</td>
</tr>
</table>
Upvotes: 1
Views: 12381
Reputation: 10698
var $this=$(this);
var quantity=$this.val();
to
var quantity = parseInt($(this).val());
$this
to access .val()
,var inventory=$(this).next('td, .item_inventory').text();
to
var inventory = parseInt( $(this).closest('tr').find('.item_inventory').html());
.item_inventory
is not a direct sibling of your .item_quantity
field, so next()
won't retrieve the DOM element. Consider finding the parent of both elements, and then get your element with find()
.The result of two string comparison is not what you need : the string comparison is going to compare each character of both string, one by one, and at the end determine the result of your comparison.
Example :
If '10' and '8' are compared, then when it will compare the two string, it will compare both it will compare '1' and '8', and then '0' and nuts.
At that moment, '1' will be closer to the start of the alphabet than '8', and then your test will return false, whatever the following character are.
See this article for further details.
Working fiddle available.
Upvotes: 3