Kim
Kim

Reputation: 33

How to use jQuery to compare two values?

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 :

JS

    $('.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');
        }            
    });               
});

HTML

<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

Answers (1)

Maen
Maen

Reputation: 10698

Changes

var $this=$(this);        
var quantity=$this.val(); 

to

var quantity = parseInt($(this).val());        
  1. You don't have to instantiate $this to access .val(),
  2. You have to parse the value into an int, otherwise it's a string which is returned. See below for explanations.

var inventory=$(this).next('td, .item_inventory').text();

to

var inventory = parseInt( $(this).closest('tr').find('.item_inventory').html());
  1. .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().
  2. You still have to parse the value to an int.

Why an int and not a string?

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

Related Questions