Nimitz E.
Nimitz E.

Reputation: 95

jQuery Math Operation on Multiple Elements

I have a simple invoicing page so I can invoice my client, however when I am going to perform multiplication to the quantity and price, the row total is not adding. Here's my jQuery so far.

$(":input").bind('keypress keydown keyup change', function(){
  var price = parseFloat($(this).closest('.tr').find('.price').val(),10),
  var qty = parseFloat($(this).closest('tr').find('.quantity').val(),10);
  var v = '';
  if(!isNaN(price) && !isNaN(qty)) {
    v = price * qty;
  }
  $(this).closest('tr').find('.rowtotal').val(v.toString());
});

And this is my HTML:

    <table>
    <tr>
        <td>1</td>
        <td><input name="item_name[]"class="form-control"></td>
        <td><input name="item_description[]"class="form-control"></td>
        <td><input name="item_price[]"class="form-control price"></td>
        <td><input name="item_quantity[]"class="form-control quantity"></td>
        <td><span class="rowtotal">0.00</span></td>
      </tr>
    <tr>
        <td>2</td>
        <td><input name="item_name[]"class="form-control"></td>
        <td><input name="item_description[]"class="form-control"></td>
        <td><input name="item_price[]"class="form-control price"></td>
        <td><input name="item_quantity[]"class="form-control quantity"></td>
        <td><span class="rowtotal">0.00</span></td>
      </tr>
    </table>

Now on my page, it shows no error while reviewing the console, but it does not perform the operation that I have created following this post "Automatically updating input field with math using jquery?"

Any help is appreciated.

TIA

Upvotes: 0

Views: 927

Answers (1)

CodingIntrigue
CodingIntrigue

Reputation: 78525

You've got a typo in this line:

var price = parseFloat($(this).closest('.tr').find('.price').val(),10),
                                        ^^ Shouldn't be a class selector

Should be:

var price = parseFloat($(this).closest('tr').find('.price').val(),10),

Next line is fine. Additionally, you can replace all those events with:

$(":input").on("input", function() {
    // Triggers on any input event
});

You also have a few other issues:

  1. There is no overload for parseFloat which takes two parameters
  2. You are using .val() to set the text of the span. You need to use .text() instead
  3. You should probably cache the <tr> selector. You don't need to go find it each time.
$(":input").on('input', function(){    
    var $tr = $(this).closest("tr");
        var price = parseFloat($tr.find('.price').val()),
            qty = parseFloat($tr.find('.quantity').val());
        var v = '';
        if(!isNaN(price) && !isNaN(qty)) {
            v = price * qty;
        }
        $tr.find('.rowtotal').text(v.toString());
    });

Working Example

Upvotes: 1

Related Questions