I have this text inputs, dynamically generated by jquery. but basically, if you see from HTML POV, it look like this :
<div class="po-row">
<input class="po-quantity">
<input class="po-price">
</div>
<div class="po-row">
<input class="po-quantity">
<input class="po-price">
</div>
<div class="po-row">
<input class="po-quantity">
<input class="po-price">
</div>
now, I want to do this calculation :
each po-row must have subtotal, calculated by po-quantity * po-price
all subtotal from each row will be summed into total. here's what I've done but only works for first row :
$(".po-row").each(function(){
$(".po-price").blur(function(){
var quantity = $(".po-quantity").val();
var price = $(".po-price").val();
var subtotal = quantity * price;
$(".total").text(subtotal);
});
});
how to make jquery each literation works in this case? thank you
You need to amend the logic to count all rows within the blur() handler, and restrict the selector to the price and quantity fields within the current row of the loop. Try this:
$(document).on('blur', '.po-price', function () {
var subtotal = 0;
$('.po-row').each(function() {
var quantity = $(this).find(".po-quantity").val();
var price = $(this).find(".po-price").val();
subtotal += quantity * price;
});
$(".total").text(subtotal);
});
Example fiddle
Note that I used document as the primary selector in the example. For your working code you should use the closest parent element of .po-price which is available in the DOM on page load.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With