quantity and remove item in shopping cart - javascript

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);
});

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>

Javascript/jQuery/Datatables sum values triggered by checkboxes

I can't figure out how to correct my javascript to make it work correctly. My goal is to have a sum of values in the table footer, picking up only checked rows. Single rows selection works fine, but using the thead checkbox to add 'checked' property to every row displayed it doesn't trigger the action. Here is my code:
Javascript
//check all
$("#check-all").click(function () {
$(".data-check").prop('checked', $(this).prop('checked'));
});
$('#sumchecked').html('KG selezione: ');
$('#inventario', 'thead').on('change', 'input[type="checkbox"]', function(){
var totalSUM = 0;
$('#sumchecked').html('KG selezione: ' +totalSUM.toFixed(3));
$('tr:has(:checked)').each(function () {
var getValue = parseFloat($(this).find("td:eq(3)").html().replace(",", "."));
totalSUM += getValue;
$('#sumchecked').html('KG selezione: ' +totalSUM.toFixed(3));
});
});
HTML Markup
<table id="inventario" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th><input type="checkbox" id="check-all"></th>
<th>N° Collo</th>
<th>Ordine</th>
<th>KG</th>
<th>Operatore</th>
<th><span style="font-size:1.5em;" title="Cimosa" class="icon-scissors-cutting-by-broken-line"></span></th>
<th><span style="font-size:1.5em;" title="Specola" class="icon-silk"></span></th>
<th>Falli</th>
<th>Note</th>
<th>Data Produzione</th>
<th>Stato</th>
<th>Consegna</th>
<th>Azioni</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th></th>
<th><div id="sumchecked"></div></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
Php controller in Codeigniter, ajax_list function used to generate table data
public function ajax_list()
{
$list = $this->packing->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $pezza) {
$no++;
$row = array();
$row[] = '<input type="checkbox" class="data-check" value="'.$pezza->n_pezza.'">';
$row[] = $pezza->n_pezza;
$row[] = $pezza->ID_ordine;
$row[] = number_format($pezza->kg_pezza,3,",",".");
$row[] = $pezza->nome_operatore;
if($pezza->selvedge == '1'){
$row[] = '<span style="font-size:1.5em;" class="glyphicon glyphicon-ok-sign"></span>';
}else{
$row[] = '';
}
if($pezza->specola == '1'){
$row[] = '<span style="font-size:1.5em;" class="glyphicon glyphicon-ok-sign"></span>';
}else{
$row[] = '';
}
$row[] = $pezza->falli;
$row[] = $pezza->note;
$row[] = $this->conversione1($pezza->data);
if ($pezza->stato == '1'){
$row[] = '<span style="font-size:1.5em;" title="Consegnata"class="icon-logistics-delivery-truck-in-movement"></span>';
$row[] = $this->conversione2($pezza->data_consegna);
}else{
$row[] = '<span style="font-size:1.5em;" title="Magazzino" class="icon-warehouse"></span>';
$row[] = '';
}
$row[] = '<div class="btn-group btn-group-justified" style="width:136px">
<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Modifica" onclick="modifica_pezza('."'".$pezza->n_pezza."'".')"><i class="glyphicon glyphicon-pencil"></i></a>
<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Info Filati" onclick="info_pezza('."'".$pezza->n_pezza."'".')"><i class="glyphicon glyphicon-info-sign"></i></a>
<a class="btn btn-sm btn-danger" href="javascript:void(0)" title="Cancella" onclick="cancella_pezza('."'".$pezza->n_pezza."'".')"><i class="glyphicon glyphicon-trash"></i></a>
</div>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->packing->count_all(),
"recordsFiltered" => $this->packing->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
This is my output if I check the first checkbox in thead
output sum checkboxes
Suggestions?
Thanks to everyone who will take some time to read and solve my problem.
Andy
It's easier to generate HTML code in #sumchecked on server side and put the attribute visibility: hidden to it. When you select a row, you do not need to run through all the selected rows every time. To minimize DOM traversing, it is better to request the current value of the total sum, and then add / subtract the price of the selected item to / from it. To get the sum of all selected items, simply insert in #checked-prices-total-sum the value from #totalkg.
For example, I took a 3 rows from your HTML table only with price columns and changed the code of your script:
$(document).ready(function() {
$("#check-all").click(function() {
var isChecked = $(this).prop('checked');
$(".data-check").prop('checked', isChecked);
var $sumchecked = $('#sumchecked');
var $totalSum = $('#checked-prices-total-sum');
if (isChecked) {
$totalSum.html($('#totalkg').html());
$sumchecked.css('visibility', 'visible');
} else {
$totalSum.html(0);
$sumchecked.css('visibility', 'hidden');
}
});
$('#inventario-data').on('change', 'input[type="checkbox"]', function(){
var $sumchecked = $('#sumchecked');
var $totalSum = $('#checked-prices-total-sum');
var totalSumValue = parseFloat($totalSum.html());
var price = parseFloat($(this).parent().next().next().html().replace(",", "."));
if ($(this).is(':checked')) {
totalSumValue += price;
} else {
totalSumValue -= price;
}
$totalSum.html(totalSumValue.toFixed(3));
totalSumValue > 0 ? $sumchecked.css('visibility', 'visible') : $sumchecked.css('visibility', 'hidden');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<table id="inventario" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th><input type="checkbox" id="check-all"></th>
<th>N° Collo</th>
<th>Ordine</th>
</tr>
</thead>
<tbody id="inventario-data">
<tr>
<td><input type="checkbox" class="data-check"></td>
<td>test</td>
<td>10,200</td>
</tr>
<tr data-rowid="2">
<td><input type="checkbox" class="data-check"></td>
<td>test</td>
<td>30,400</td>
</tr>
<tr data-rowid="3">
<td><input type="checkbox" class="data-check"></td>
<td>test</td>
<td>50,600</td>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th><div id="sumchecked" style="visibility: hidden;">KG selezione: <span id="checked-prices-total-sum">0</span></div></th>
<th>Tot. KG <span id="totalkg">91,200</span></th>
</tr>
</tfoot>
</table>

Javascript- Add row dynamically contain dropbox and formula

I have a table consist of 5 column: Code, Name, Qty, Price, and Total.
Code contain a dropbox menu which dynamically retrieve from another table. If user click the dropbox and select a code, name of the item will appear automatically in Name column.
For Total column, the value will appear from multiplying Qty and Price. The multiply script I used is:
<script language="javascript" type="text/javascript">
function multiply()
{
a=Number(document.calculator.qty.value);
b=Number(document.calculator.price.value);
c=a*b;
document.calculator.total.value=c;
}
</script>
My code for the table as below:
<table id="theTable" border="1">
<script>
var maxID = 0;
function getTemplateRow() {
var x = document.getElementById("templateRow").cloneNode(true);
x.id = "";
x.style.display = "";
x.innerHTML = x.innerHTML.replace(/{id}/, ++maxID);
return x;
}
function addRow() {
var t = document.getElementById("theTable");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
r.parentNode.insertBefore(getTemplateRow(), r);
}
</script>
<thead>
<tr>
<th> Code </th>
<th> Name </th>
<th> Qty </th>
<th> Price </th>
<th> Total </th>
<tr>
</thead>
<tbody>
<tr id="templateRow">
<td type="text" name="code" id="code"/readonly>
<?php
mysql_connect("localhost","root","");
mysql_select_db("inventory");
$result = mysql_query("select * from input_code_data");
$jsArray = "var code = new Array();\n";
echo '<select name="code" onchange="changeValue(this.value)">';
echo '<option></option>';
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['code'] . '">' . $row['code'] . '</option>';
$jsArray .= "code['" . $row['code'] . "'] = {name:'" . addslashes($row['name']) . "',desc:'".addslashes($row['name'])."'};\n";
}
echo '</select>';
?>
</td>
<td><input type="text" name="name" id="name"/readonly>
<script type="text/javascript">
<?php echo $jsArray; ?>
function changeValue(id){
document.getElementById('code').value = code[id].name;
document.getElementById('name').value = code[id].desc;
};
</script>
</td>
<td><input type="text" name="qty"></td>
<td><input type="text" name="price"></td>
<td><input type="text" name="total" /readonly><INPUT type="button" value="Click" onclick="javascript:multiply();"></td>
</tr>
</tbody>
</table>
<INPUT type='button' value='+' onclick="addRow('theTable')" />
If I click add row, then a new row will appear and the format is right. The problem is, when I select a code (from the dropbox) in second row, the name appear in the first row instead, not in the second row. Another problem, Click button for multiply isn't working in the second row.
Would anybody tell me how I fix this? Thanks.
It's because your changeValue(id) function is being called with the select field's value, not the row Id. Additionally, you're getting element by static id's instead of passing them in. HTML assumes that an Id will only appear once per page, you're breaking that so it always returns the first match.
EDIT for some example code:
This deals with some of the issues (if I'm understanding you properly). You might find the MDN docs helpful around how ids and other selectors work.
multiply suffers from the same issues as your original code, but you should be able to figure it out based on what is below:
<table id="theTable" border="1">
<thead>
<tr>
<th> Code </th>
<th> Name </th>
<th> Qty </th>
<th> Price </th>
<th> Total </th>
<tr>
</thead>
<tbody>
<tr class="templateRow" id="invoice-line-1">
<td class="code">
<select onchange="changeValue(this.value, 'invoice-line-1')">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<!-- etc. -->
</select>
<span></span>
</td>
<td class="name"></td>
<td><input type="text" name="qty"></td>
<td><input type="text" name="price"></td>
<td>
<input type="text" name="total" /readonly>
<input type="button" value="Click" onclick="javascript:multiply();">
</td>
</tr>
</tbody>
</table>
<input type='button' value='+' onclick="addRow('theTable')" />
<script type="text/javascript">
var codes = {
"1": {value: 1, name: "Option 1"},
"2": {value: 2, name: "Option 2"},
// etc.
},
numRows = 1;
function changeValue(value, id){
document.querySelector('#' + id + ' td.name').innerHTML = codes[value].name;
document.querySelector('#' + id + ' td.code > span').innerHTML = code[value].value;
};
function addRow() {
var newRow = document.getElementById("invoice-line-1").cloneNode(true),
table = document.querySelector("#theTable > tbody");
newRow.id = "invoice-line-" + (numRows = numRows + 1);
table.appendChild(rewRow);
document.querySelector("#invoice-line-" + numRows + " .code > select").setAttribute('onchange', "changeValue(this.value, 'invoice-line-" + numRows + "')");
}
</script>

JavaScript Total Cost after deleting Item

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);
});

Categories

Resources