Reputation: 95
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
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:
parseFloat
which takes two parameters.val()
to set the text of the span. You need to use .text()
instead<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());
});
Upvotes: 1