Reputation: 85
I want to add single column values via javascript
when user enter quantity than the quantity multiply with the price column and shown into the 'your bill' column. The problem is that when user click on order button than all the values from 'your bill' column will add and show on the screen.
kindly tell me how can i sum all values from 'your bill column'
My view file is
<tbody>
<?php $i=0; foreach($result as $row){
?>
<tr>
<th class="item-lists">
<?php echo $row->recipe_name;?>
</th>
<th class="pre-top">
<?php echo $row->quantity;?>
</th>
<th class="pr-right">
<span id="priceT<?php echo $i;?>" ><?php echo $row->price;?></span>
</th>
<th class="pr-right">
<input type="text" class="container" value="" onfocus="this.value = '';" onblur=";}" style="width: 60px" id="quantityT<?php echo $i;?>" onkeyup="CalculatePrice (<?php echo $i;?>)">
</th>
<th class="clearfix">
<input type="text" class="container" value="" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '';}" style="width: 60px"id="TPrice<?php echo $i;?>">
</th>
</tr>
<?php
$i++;
} ?>
</tbody>
and javascript code
function CalculatePrice (id) {
var startP = parseInt (document.getElementById ("priceT"+id).innerHTML);
var startQ = parseInt (document.getElementById ("quantityT"+id).value);
var Bill = 0;
if (!isNaN ( startP)&&!isNaN(startQ))
{var Bill = startP * startQ}
document.getElementById ("TPrice"+id).value = Bill;
}
Upvotes: 1
Views: 1963
Reputation: 1840
Add a class to the input fields of the "Your bill" column:
<input type="text" class="container row-total" value="" />
Assuming your "Order" button has id "order-btn":
<button id="order-btn">Order</button>
Use a listener and calculate the total:
document.getElementById('order-btn').addEventListener('click',function(){
var rowTotals = document.getElementsByClassName('row-total');
var orderTotal = 0;
for(var i = 0; i < rowTotals.length; i++){
orderTotal += parseFloat(rowTotals[i].value);
}
alert(orderTotal);
});
A jQuery alternative:
$(function(){
$('#order-btn').click(function(){
var orderTotal = 0;
$('.row-total').each(function(){
orderTotal += parseFloat($(this).val());
});
alert(orderTotal);
});
});
Upvotes: 1
Reputation: 520
I think this could works :
First set a new class to the <th class="clearfix">
like... <th class="clearfix product-price">
and add a data-price
to your inputs with the price (for security reasons, an user can change the value of an input text).
Then with javascript :
var order = document.getElementById('order');
var totalPrice = 0;
order.addEventListener('click', function(){
var productsPrice = document.getElementsByClassName('product-price');
console.log(productsPrice);
for(var i = 0; i < productsPrice.length; i++){
totalPrice += parseInt(productsPrice[i].dataset.price);
}
alert("Total = "+totalPrice);
});
I made a fiddle.
Personally I used span
instead of text input
for the reason I explained before.
Upvotes: 0