JCD JCD - 1 month ago 12
jQuery Question

Calculate Arrays with input field instead of span or div

I'm trying to do a simple calculation onblur with arrays but it's not firing. If I change it to a span or div it works fine. Why isn't it working with an input field?

I need it to be an input field because it's easier to store the values in a database.

<input type="text" class="input-small" name="partnumber[]">
<input type="text" class="input-small" name="partdescription[]" >
<input type="text" class="input-small" name="partprice[]" onblur="doCalc(); calculate(); ">
<input type="text" class="input-small" name="partquantity[]" onblur="doCalc(); calculate(); ">
<input type="text" readonly class="input-small parttotal" name="parttotal[]" >


Calculation

function doCalc() {
var total = 0;

$('tr').each(function() {
$(this).find('.parttotal').html($('input:eq(2)', this).val() * $('input:eq(3)', this).val());
});
$('.parttotal').each(function() {
total += parseInt($(this).text(),10);
});
}

Answer

Firstly, I wouldn't use inline events.. Here I've used delegated events, an advantage here if you dynamically add any more lines, it will still work..

Next make sure each line has some sort of wrapper for each line, here I've used a simple DIV. Yousr might be your TR..

The rest then becomes easy, as can be seen here, this example I've just included the price, qty & total, and done 2 lines for testing..

function calc() {
  var h = $(this).closest('div');
  var qty = h.find('[name="partquantity[]"]');
  var price = h.find('[name="partprice[]"]');
  var total = h.find('[name="parttotal[]"]');
  total.val(qty.val() * price.val());
}

$('body').on('blur', '[name="partprice[]"],[name="partquantity[]"]', calc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <input type="text" class="input-small" name="partprice[]">
  <input type="text" class="input-small" name="partquantity[]">
  <input type="text" readonly class="input-small parttotal" name="parttotal[]" >
</div>

<div>
  <input type="text" class="input-small" name="partprice[]">
  <input type="text" class="input-small" name="partquantity[]">
  <input type="text" readonly class="input-small parttotal" name="parttotal[]" >
</div>