Reputation: 521
I have these dynamically created text fields using jQuery:
<div class="row"><input type="text" id="product_price_1"><input type="text" id="product_quantity_1"><input type="text" id="product_total_price_1"></div>
<div class="row"><input type="text" id="product_price_2"><input type="text" id="product_quantity_2"><input type="text" id="product_total_price_2"></div>
<div class="row"><input type="text" id="product_price_3"><input type="text" id="product_quantity_3"><input type="text" id="product_total_price_3"></div>
the values come from the database and the number of rows vary.
this is what i did in my .js file:
$('#product_quantity_1').change(function() {
$('#product_total_price_1').val(
$('#product_price_1').val()*$('#product_quantity_1').val()
);
});
what i did works, the the total price changes when i input a different product quantity
i also want to access the other input fields, and put a .change() event but the number would always vary
how to deal with this? thanks!
Upvotes: 0
Views: 94
Reputation: 388316
You can assign a common class to related elements, like a common class to all price elements ex
<div class="row">
<input type="text" id="product_price_1" class="product_price">
<input type="text" id="product_quantity_1" class="product_quantity">
<input type="text" id="product_total_price_1" class="product_total_price">
</div>
<div class="row">
<input type="text" id="product_price_2" class="product_price">
<input type="text" id="product_quantity_2" class="product_quantity">
<input type="text" id="product_total_price_2" class="product_total_price">
</div>
<div class="row">
<input type="text" id="product_price_3" class="product_price">
<input type="text" id="product_quantity_3" class="product_quantity">
<input type="text" id="product_total_price_3" class="product_total_price">
</div>
then
$('.product_quantity').change(function () {
$(this).next('.product_total_price').val(($(this).prev('.product_price').val() * this.value) || 0);
});
Demo: Fiddle
Upvotes: 3