JavaScript Total Cost after deleting Item - javascript

I have foreached some items that I sell :
<?php foreach ($selectedItems as $item): ?>
<tr class="product" data-price="<?= $item->price ?>">
<th class="items"><?= $item->name ?></th>
<th id="price" class="items middle-th "> <!-- the 3rd column -->
<div >
<button type="button" class="sub" title="If u want less quantity">-</button>
<input class="quantityTxt quantity " id="quantity" name="quantity[]" type="text" value="1" onchange="quantityChange(this)" >
<button type="button" class="add" title="If u want more quantity" >+</button>
</div>
</th>
<th>
<span class="productTotal"></span>
</th>
<th id="price" class="items">
<button class="remove_field" data-value="<?= $item->price ?>" title="Click to delete product" >
<div class="glyphicon glyphicon-trash" ></div>
</button>
</th>
</tr>
<?php endforeach; ?>
</table>
<div class="row-fluid well">
<strong id="total"> Total: € <span id="sum"> </span> </strong></div>
<div class="payment">
I set onClick to delete the row after the button is pressed so to delete the rows so I need when I delete the row , to minus the total cost of the product form the total sum . Later is my Script Code where I have all of the things ,but I left only to minus from Total the Cost of the deleted row .
$('table').on('click', 'button.remove_field', function () {
$(this).closest('tr').remove();
var id = $(this).attr('data-value');
console.log(id);
});
$('.add').click(function () {
var target = $('.quantity', this.parentNode)[0];
target.value = +target.value + 1;
updateTotal();
});
$('.sub').click(function () {
var target = $('.quantity', this.parentNode)[0];
if (target.value > 1) {
target.value = +target.value - 1;
}
updateTotal();
});
var updateTotal = function () {
var sum = 0;
//Add each product price to total
$(".product").each(function () {
var price = $(this).data('price');
var quantity = $('.quantityTxt', this).val();
//Total for one product
var subtotal = price * quantity;
//Round to 2 decimal places.
subtotal = subtotal.toFixed(2);
//Display subtotal in HTML element
$('.productTotal', this).html(subtotal);
});
// total
$('.productTotal').each(function () {
sum += Number($(this).html());
});
$('#sum').html(sum.toFixed(2));
};
//Update total when quantity changes
$(".product").keyup(function () {
updateTotal();
});
//Update totals when page first loads
updateTotal();
// set this from local
$('span.productTotal').each(function () {
$(this).before("€");
});
// unit price
$('.product').each(function () {
var $price = $(this).parents("div").data('price');
$(this).before($price);
});

Related

How to properly distribute js code for php foreach?

Have php foreach in file
<?php
foreach($_SESSION['cart'] as $item):
$sqlcartprod = mysqli_query(db(),"SELECT * FROM products WHERE id='".$item['product']."' ");
$rowcartprod = mysqli_fetch_array($sqlcartprod);
?>
<tr>
<td class="shoping__cart__item">
<img src="<?=$rowcartprod['ikonka']?>" width="101" alt="">
<h5><?=$rowcartprod['name_'.$lang]?></h5>
</td>
<td class="shoping__cart__price" >
<span id="priceprod"><?=$rowcartprod['price']?></span> azn
</td>
<td class="shoping__cart__quantity">
<div class="quantity">
<div class="pro-qty">
<input type="text" style="cursor: default" readonly value="<?=$item['qty']?>">
</div>
</div>
</td>
<td class="shoping__cart__total" id="totalprice">
<?=$item['price']*$item['qty']?> azn
</td>
</tr>
<?php endforeach; ?>
for this piece of code:
<div class="quantity">
<div class="pro-qty">
<input type="text" style="cursor: default" readonly value="<?=$item['qty']?>">
</div>
</div>
have JS code:
var proQty = $('.pro-qty');
proQty.prepend('<span class="dec qtybtn">-</span>');
proQty.append('<span class="inc qtybtn">+</span>');
proQty.on('click', '.qtybtn', function () {
var $button = $(this);
var oldValue = $button.parent().find('input').val();
if ($button.hasClass('inc')) {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$button.parent().find('input').val(newVal);
var Price = document.getElementById('priceprod').innerText;
var Tprice = document.getElementById('totalprice');
if (Price[i] > 0) {
Tprice.textContent = (Price[i] * newVal) + ' azn';
}
});
The issue is that when I click on qtybtn + or qtybtn -, the js code works only for the first product in the shopping list, even if there are 2,3 or more products in the list. I tried to separate inside the js code with loops, but then the js code somehow stops working at all. How to distribute correctly so that the js code works for each product separately?

Not able to insert the data in input field of form

I have a form, there is a button (+sign)on the form which appends a row to insert the value .In my form i am able to enter the value on the first row both fields( stationerytype and stationeryqty). But once I append a new row by clicking plus button I am not able to insert any value on staionerytype field of second row while I'm able to insert the value in the stationeryqty field of second row.
My code is:
<table class="table table-bordered" id="tb" >
<tr class="tr-header">
<th class= "col-md-1" align="centre">Sl.No.</th>
<th class= "col-md-6" align="centre">STATIONARY TYPE</th>
<th class= "col-md-4" align="centre">STATIONARY QUANTITY</th>
<th class= "col-md-1"><span class="glyphicon glyphicon-plus"></span></th>
</tr>
<tr>
<?php
for($i=1;$i<=1;$i++)
{
?>
<td><input type="text" style="text-decoration: none" name="slno" value= "<?php echo $i; ?>" ></td>
<td><input type="text" style="text-decoration: none" name="stationerytype" ></td>
<td><input type="number" name="stationeryqtyrecd" id="stationeryqtyrecd" min="0"></td>
<td><a href='javascript:void(0);' class='remove'><span class='glyphicon glyphicon-remove'></span></a></td>
</tr>
<?php }?>
</table>
<button type="submit" name="add" class="btn btn-info" align="middle" >ADD </button>
<script>
var max = 4;
var count = 1;
$(function(){
$('#addMore').on('click', function() {
if(count <= max ){
var data = $("#tb tr:eq(1)").clone(true).appendTo("#tb");
data.find("input").val('');
debugger;
data.find("input")[0].value=++count;
}else{
alert("Sorry!! Can't add more than five samples at a time !!");
}
});
$(document).on('click', '.remove', function() {
var trIndex = $(this).closest("tr").index();
if(trIndex>1) {
$(this).closest("tr").remove();
} else {
alert("Sorry!! Can't remove first row!");
var trIndex = $(this).closest("tr").index();
if(trIndex>1) {
$(this).closest("tr").remove();
count--;
// get all the rows in table except header.
$('#tb tr:not(.tr-header)').each(function(){
$(this).find('td:first-child input').val(this.rowIndex);
})
}
});
});
</script>
</div>

Auto calculate sum for dynamically add and delete rows - jquery

How calculate sum for dynamically add and delete rows, i can create some code but its working only add row, when i click the som wont calculating, I just need auto calculate sum when adding rows and deleting rows.
When i delete rows the total sum not decrese.
Here is fiddle..
FIDDLE HERE
Here is my snippet..
$(document).ready(function() {
var counter = 0;
$("#add_Row").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" id="cashdeb' + counter + '" data-action="sumDebit" name="debit" placeholder="Debit amount"/></td>';
cols += '<td><button type="button" class="adRow ibtnDel" style="width:70%;">x</button></a></td>';
newRow.append(cols);
var defVal = $("select[name=acctname]").find(":selected").val();
if (defVal) {
$("select[name=accountName]").find(`option[value=${defVal}]`).hide();
}
$("table.order-list").append(newRow);
setValCashVal('accountName'.concat(counter));
bindScript();
counter++;
});
// delete function
$("table.order-list").on("click", ".ibtnDel", function(_event) {
$(this).closest("tr").remove();
counter -= 1
});
});
/* total */
$('body').on('change', '[data-action="sumDebit"]', function() {
var total = 0;
$('[data-action="sumDebit"]').each(function(_i, e) {
var val = parseFloat(e.value);
if (!isNaN(val))
total += val;
});
$('#totaldbt').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover order-list" id="tab_logic">
<thead>
<th class="text-center">
Debit*
</th>
</thead>
<tbody>
<input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
</tbody>
</table>
</div>
</div>
</div>
<!-- total -->
<div class="row">
<div class="col-6">
<div class="cashTotal">
<p class="tableTotal">Total:</p>
</div>
</div>
<div class="col-6">
<input type="number" class="totaldeb" id="totaldbt" name="total" placeholder="Total Debit Amount" readonly>
</div>
</div>
change event doesn't fires when you delete a row. I would suggest to have a separate function that evaluates the total and call it on change as well as on row delete.
see fiddle: https://jsfiddle.net/46fnv9ux/
$("table.order-list").on("click", ".ibtnDel", function(_event) {
$(this).closest("tr").remove();
counter -= 1
evaluateTotal()
});
$('body').on('change', '[data-action="sumDebit"]', function() {
evaluateTotal();
});
function evaluateTotal() {
var total = 0;
$('[data-action="sumDebit"]').each(function(_i, e) {
var val = parseFloat(e.value);
if (!isNaN(val))
total += val;
});
$('#totaldbt').val(total);
}
just do the same thing when delete the row which you have done on add.
$(document).ready(function() {
var counter = 0;
$("#add_Row").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" id="cashdeb' + counter + '" data-action="sumDebit" name="debit" placeholder="Debit amount"/></td>';
cols += '<td><button type="button" class="adRow ibtnDel" style="width:70%;">x</button></a></td>';
newRow.append(cols);
var defVal = $("select[name=acctname]").find(":selected").val();
if (defVal) {
$("select[name=accountName]").find(`option[value=${defVal}]`).hide();
}
$("table.order-list").append(newRow);
setValCashVal('accountName'.concat(counter));
bindScript();
counter++;
});
// delete function
$("table.order-list").on("click", ".ibtnDel", function(_event) {
$(this).closest("tr").remove();
counter -= 1
var total = 0;
$('[data-action="sumDebit"]').each(function(_i, e) {
var val = parseFloat(e.value);
if (!isNaN(val))
total += val;
});
$('#totaldbt').val(total);
});
});
/* total */
$('body').on('change', '[data-action="sumDebit"]', function() {
var total = 0;
$('[data-action="sumDebit"]').each(function(_i, e) {
var val = parseFloat(e.value);
if (!isNaN(val))
total += val;
});
$('#totaldbt').val(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover order-list" id="tab_logic">
<thead>
<th class="text-center">
Debit*
</th>
</thead>
<tbody>
<input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
</tbody>
</table>
</div>
</div>
</div>
<!-- total -->
<div class="row">
<div class="col-6">
<div class="cashTotal">
<p class="tableTotal">Total:</p>
</div>
</div>
<div class="col-6">
<input type="number" class="totaldeb" id="totaldbt" name="total" placeholder="Total Debit Amount" readonly>
</div>
</div>
The delete button click event is not recalculating the total.
The answer by #Devis & Bilal will add all the values to find the sum. Instead you can just subtract the deleted row's value from total.
Modify the delete function as below, to subtract the deleted value from total.
// delete function
$("table.order-list").on("click", ".ibtnDel", function(_event) {
counter -= 1
var total = $('#totaldbt').val();
var delVal = $(this).closest("tr").find('input').val();
var val = parseFloat(delVal);
if (!isNaN(val))
total -= val;
$('#totaldbt').val(total);
$(this).closest("tr").remove();
})
;
I moved the calculation to a function calculateTotal and add an event for the delete button to recalculate total when any row is deleted:
$(document).ready(function() {
var counter = 0;
$("#add_Row").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" id="cashdeb' + counter + '" data-action="sumDebit" name="debit" placeholder="Debit amount"/></td>';
cols += '<td><button type="button" class="adRow ibtnDel" style="width:70%;">x</button></a></td>';
newRow.append(cols);
var defVal = $("select[name=acctname]").find(":selected").val();
if (defVal) {
$("select[name=accountName]").find(`option[value=${defVal}]`).hide();
}
$("table.order-list").append(newRow);
setValCashVal('accountName'.concat(counter));
bindScript();
counter++;
});
// delete function
$("table.order-list").on("click", ".ibtnDel", function(_event) {
$(this).closest("tr").remove();
counter -= 1
});
});
/* total */
$('body').on('change', '[data-action="sumDebit"]', function(){
calculateTotal();
});
$(document).on( 'click', '.ibtnDel', function () {
calculateTotal();
});
function calculateTotal(){
var total = 0;
$('[data-action="sumDebit"]').each(function(_i, e) {
var val = parseFloat(e.value);
if (!isNaN(val))
total += val;
});
$('#totaldbt').val(total);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover order-list" id="tab_logic">
<thead>
<th class="text-center">
Debit*
</th>
</thead>
<tbody>
<input type="button" class="add_Row adRow" id="add_Row" value="Add Row">
</tbody>
</table>
</div>
</div>
</div>
<!-- total -->
<div class="row">
<div class="col-6">
<div class="cashTotal">
<p class="tableTotal">Total:</p>
</div>
</div>
<div class="col-6">
<input type="number" class="totaldeb" id="totaldbt" name="total" placeholder="Total Debit Amount" readonly>
</div>
</div>
or you can do it in the following way:
$('body').on('change', '[data-action="sumDebit"]', function(){
calculateTotal();
$('#tab_logic').on( 'click', '.ibtnDel', function () {
calculateTotal();
});
});
function calculateTotal(){
var total = 0;
console.log(total);
$('[data-action="sumDebit"]').each(function(_i, e) {
var val = parseFloat(e.value);
if (!isNaN(val))
total += val;
});
$('#totaldbt').val(total);
}

quantity and remove item in shopping cart

I made the "items" from the shop to be stored in unique array in session and to be passed on the shopping cart , and I want to put quantity for each item and if I want to delete item from the shopping cart to be deleted from the array . I made the html form and quantity buttons for "plus" and "minus" , but I cant figure out how to catch the value in the input when its changed with the buttons and then to multiply it with the cost of each item so later I can get total cost ( In the code it can be seen that I set value="1" for each item , so the base value for each item is 1 ) . I made also with JS to remove the row from deleted item that I want but also didnt figure out how to delete the item from the array
This is my shopping cart :
<div class="container">
<div class="jumbotron">
<div class="container text-center">
<h3>Shopping Cart</h3>
<table class="table table-striped" >
<tr>
<th class="items" > Product </th>
<th class="items"> Quantity </th>
<th class="items"> Unit Price </th>
<th>Total Cost</th>
<th></th>
</tr>
<?php foreach ($selectedItems as $item): ?>
<tr>
<th class="items"><?= $item->name ?></th>
<th class="items ">
<div>
<button type="button" class="sub" title="If u want less quantity">-</button>
<input type="text" value="1" id="quantity" class="quantity" name="quantity[]" onchange="quantityChange(this)" >
<button type="button" class="add" title="If u want more quantity" >+</button>
</div>
</th>
<th id="price" class="items"> <?= $item->price ?></th>
<th><span class="allcost"> </span></th>
<th class="items">
<button class="remove_field " title="Click to delete product" >
<div class="glyphicon glyphicon-trash" ></div>
</button>
</th>
</tr>
<?php endforeach; ?>
</table>
<?= Html::a('Return to Shop', ['/stock/shop'], ['class' => 'btn btn-default']) ?>
<?= Html::a('Checkout', ['/stock/checkout'], ['class' => 'btn btn-default']) ?>
</div>
</div>
<script type="text/javascript">
$(document).on('click', 'button.remove_field', function () {
$(this).closest('tr').remove();
});
$('.add').click(function () {
var target = $('.quantity', this.parentNode)[0];
target.value = +target.value + 1;
target.onchange();
});
$('.sub').click(function () {
var target = $('.quantity', this.parentNode)[0];
if (target.value > 1) {
target.value = +target.value - 1;
}
target.onchange();
});
function quantityChange(sender) {
var quantity = $(sender).val();
console.log(quantity);
};
My ActionCart :
public function actionCart() {
Yii::$app->session->open();
Yii::$app->session->open();
$selectedItems = Yii::$app->session['selectedItems'];
$stockItems = Stock::find()->where(['id' => $selectedItems])->all();
$data = [
'selectedItems' => $stockItems,
];
return $this->render('cart', $data);
}
Quantity and Cost solution :
In the HTML code :
<?php foreach ($selectedItems as $item): ?>
<tr class="product" data-price="<?= $item->price ?>">
<th class="items"><?= $item->name ?></th>
<th id="price" class="items middle-th "> <!-- the 3rd column -->
<div >
<button type="button" class="sub" title="If u want less quantity">-</button>
<input class="quantityTxt quantity " id="quantity" name="quantity[]" type="text" value="1" onchange="quantityChange(this)" >
<button type="button" class="add" title="If u want more quantity" >+</button>
</div>
</th>
<th>
<span class="productTotal"></span>
</th>
<th id="price" class="items ">
<button class="remove_field " data-value="<?= $item->id ?>" title="Click to delete product" >
<div class="glyphicon glyphicon-trash" ></div>
</button>
</th>
</tr>
<?php endforeach; ?>
JavaScript Code :
$('.add').click(function () {
var target = $('.quantity', this.parentNode)[0];
target.value = +target.value + 1;
updateTotal();
});
$('.sub').click(function () {
var target = $('.quantity', this.parentNode)[0];
if (target.value > 1) {
target.value = +target.value - 1;
}
updateTotal();
});
function quantityChange(sender) {
var quantity = $(sender).val();
console.log(quantity);
}
;
var updateTotal = function () {
var sum = 0;
//Add each product price to total
$(".product").each(function () {
var price = $(this).data('price');
var quantity = $('.quantityTxt', this).val();
//Total for one product
var subtotal = price * quantity;
//Round to 2 decimal places.
subtotal = subtotal.toFixed(2);
//Display subtotal in HTML element
$('.productTotal', this).html(subtotal);
});
// total
$('.productTotal').each(function () {
sum += Number($(this).html());
});
$('#sum').html(sum.toFixed(2));
};
//Update total when quantity changes
$(".product").keyup(function () {
updateTotal();
});
//Update totals when page first loads
updateTotal();
// set this from local
$('span.productTotal').each(function () {
$(this).before("€");
});
// unit price
$('.product').each(function () {
var $price = $(this).parents("div").data('price');
$(this).before($price);
});

Doing some calculations on html table using Javascript issue

Hi i am trying to do the some calculations on HTML table using javascript code
but i am having issues getting percentage values
demo: jsfiddle
when i entered the below sample data i got this result
Quantity Unit Price Total Percentage
1 5 5 Infinity
2 5 10 2
3 5 15 1
Grand Total 30
as you can see percentage values are wrong
Percentage = Total / Grand Total
So percentage values should be like this
Percentage
0.16
0.33
0.5
Javascript
<script>
$(document).ready(function () {
$(".txtMult input").keyup(multInputs);
function multInputs() {
var mult = 0;
// for each row:
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1) * ($val2);
var $Percentage = ($total / mult) * 100;
$('.percentage', this).text($Percentage);
$('.multTotal', this).text($total);
mult += $total;
});
$("#grandTotal").text(mult);
}
});
</script>
HTML
<table>
<tr>
<th>Quantity
</th>
<th>Unit Price
</th>
<th>Total
</th>
<th>Percentage
</th>
</tr>
<tr class="txtMult">
<td>
<input name="txtbox1" class="val1" />
</td>
<td>
<input name="txtbox2" class="val2" />
</td>
<td>
<span class="multTotal">0.00</span>
</td>
<td>
<span class="percentage">0</span>
</td>
</tr>
<tr class="txtMult">
<td>
<input name="txtbox1" class="val1" />
</td>
<td>
<input name="txtbox2" class="val2" />
</td>
<td>
<span class="multTotal">0.00</span>
</td>
<td>
<span class="percentage">0</span>
</td>
</tr>
<tr class="txtMult">
<td>
<input name="txtbox" class="val1" />
</td>
<td>
<input name="txtbox" class="val2" />
</td>
<td>
<span class="multTotal">0.00</span>
</td>
<td>
<span class="percentage">0</span>
</td>
</tr>
<tr>
<td colspan="3" ">Grand Total <span id="grandTotal">0.00</span>
</td>
</tr>
</table>
Your help is much appreciated
Here is some working JS code that I tested in the fiddle:
$(document).ready(function () {
$(".txtMult input").keyup(multInputs);
function multInputs() {
var $mult = 0;
// calculate Grand total
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1) * ($val2);
$mult += $total;
});
// for each row:
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1) * ($val2);
var $Percentage = (($total / $mult)).toFixed(2);
$('.percentage', this).text($Percentage);
$('.multTotal', this).text($total);
});
$("#grandTotal").text($mult);
}
});
I calculated the grand total first then divided each row total by the grand total. Also, .toFixed(2) can be used to round to 2 decimal places if desired.

Categories

Resources