i have some input fields
<input type="text" name="quantity[]" class="est_quantity" placeholder="quantity"/>
<input type="text" name="quantity[]" class="est_quantity" placeholder="quantity"/>
<input type="text" name="quantity[]" class="est_quantity" placeholder="quantity"/>
<input type="text" name="cost[]" class="est_cost" placeholder="cost"/>
<input type="text" name="cost[]" class="est_cost" placeholder="cost"/>
<input type="text" name="cost[]" class="est_cost" placeholder="cost"/>
i need to perform some calculations.
//Calculate total Quantity, this is how i do it.
$('.est_quantity').live('keyup', function(){
var val = 0;
$('.est_quantity').each(function() {
if($(this).val().length && $(this).val() != '') {
val += Number($(this).val());
$('.est_total_quantity').html(val);
}
});
});
the above code works fine, since total quantity is the sum of all quantity[] however calculating the total cost is little different. since the calculation goes like this.
total cost = total_quantity * cost
//for each field or row.
while calculating the cost i want the value to be multiplied by it’s corresponding quantity field.
something like
var cost = $('.est_quantity').val * $('.est_cost').val();
i tried doing it this way
$('.est_cost').live('keyup', function(){
var val = 0.00;
$('.est_cost').each(function() {
if($(this).val().length && $(this).val() != '') {
var cost = $(this).val() * $('.est_quantity').val();
val += parseFloat(cost);
$('.est_total_cost').html(val.toFixed(2));
}
});
});
the above code fetch proper calculations for only first row, for rest it fetches some weird value.
how do i go with the code for proper calculations?
P.S: initially there is one row of input fields which includes quantity and cost input fields, the rest input fields are dynamically added upon click event.
thank you
in the second code sample.. you should take care that there are more than one element with
.est_quantityclass you will have to select one when you are iterating over elements with.est_costclass.something like this
notice that im using
indexparameter of each function.note:- assuming there are equal number of
.est_quantityand.est_costelements