Javascript is not doing sum of all records - javascript

I'm trying to do the sum of all cart items but it is not doing it.
It is showing only the sum of first or last item added in the cart.
What is the issue i cannot understand. I have tried by moving code in the java but no use.
Suppose i have 2 items.
Item1 total is = 100
Item2 total is = 200
Total should be 300 not only the 1 items total.
Below is my code.
Thanks in advance
<script type="text/javascript" src="js/jquery-1.12.1.min.js"></script>
<table class="table mg-bottom-45 refresh" id="myTable">
<thead>
<tr>
<th class="product-cart-price"><span>PRICE</span></th>
<th class="product-cart-price"><span>TOTAL</span></th>
</tr>
</thead>
<tbody>
<?php
include ('inc/db.php');
$citem = "select * from orders_temp
where user_id = 1 order by id
";
$ciquery = $dba2->query($citem);
while ($cifetch = $ciquery->fetch_assoc()){
$orderID = $cifetch['id'];
$userID = $cifetch['user_id'];
?>
<td class="product-cart-thumbnail">
<input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
data-price="" value="<?php echo $cifetch['qty']; ?>"
class="un quant" />
</td>
<td class="product-cart-thumbnail">
<input name="quantity" type="text" data-id="<?php echo $orderID; ?>"
data-price="<?php echo $cifetch['price']; ?>"
value="<?php echo $cifetch['price']; ?>" class="un pricex" />
</td>
<?php } ?>
<td class="totalAmount"></td>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function() {
updatexx<?php echo $orderID; ?>();
function updatexx<?php echo $orderID; ?>() {
var sumx = '';
$('#myTable > tbody > tr').each(function() {
var quantityx = $(this).find('.quant').val();
var pricex = $(this).find('.pricex').attr('data-price').replace(',', '.');
var amountx = (quantityx * pricex).toFixed(3);
sumx += amountx;
});
$('.totalAmount').text(sumx);
}
});
</script>

First, please make sure that your loop is running multiple times (same number of products in cart).
$('#myTable > tbody > tr').each(function() {})
so that the above loop iterate exact number times as per required.
You should make some changes in code as follows:
var sumx = 0.00;
and in loop code should be
sumx += parsefloat(amountx);

So here is the solution with some changes in my code.
Now it is working perfectly as required. It is doing the sum of all items and everything what i want.
<table class="table mg-bottom-45 refresh" id="myTable">
<tbody>
<?php
$i = 0;
//error_reporting(0);
$ses_mem = 1;
include ('inc/db.php');
$citem = "select id, user_id, qty, org_price from orders_temp
where user_id = '".$ses_mem."' and status = 1
order by id
";
$ciquery = $dba2->query($citem);
while ($cifetch = $ciquery->fetch_assoc()){
$orderID = $cifetch['id'];
?>
<tr>
<script type="text/javascript" src="js/jquery-1.12.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
updatexx<?php echo $orderID; ?>();
function updatexx<?php echo $orderID; ?>() {
var sumx = 0.000;
var quantity;
$('#myTable > tbody > tr').each(function() {
quantity = $(this).find('.quant').val();
var price = $(this).find('.pricex').attr('data-price').replace(',', '.');
var amountx = (quantity * price);
var munterx = amountx.toFixed(3);
sumx += amountx;
$(this).find('.amountx<?php echo $orderID; ?>').text('' + munterx);
});
var sumxx = sumx.toFixed(3);
$('.total').text(sumxx);
}
});
</script>
<td class="single-qty" style="border: 0;">
<input id="<?php echo $orderID; ?>" name="quantity" type="text"
data-id="<?php echo $orderID; ?>"
data-price="" value="<?php echo $cifetch['qty']; ?>"
class="un quant" />
</td>
<td class="product-cart-price pricex" data-price="<?php echo $cifetch['org_price']; ?>">
</td>
<td class="amountx<?php echo $orderID; ?>">
</td>
</tr>
<?php } ?>
</tbody>
</table>
<table class="table">
<tbody>
<tr>
<td>Sub Total (RS)</td>
<td class="text-right"
style="text-shadow: 2px 2px 3px #999999; font-weight: bold;
color: black; direction: rtl;">
<span class="total">
</span>
</td>
</tr>
</tbody>
</table>

Related

How to add when a checkbox is checked and deduct when unchecked in Javascript when html id is a php variable

I am trying to total a particular column amounts from a php array when a checkbox is checked and deduct from the total when it is unchecked. I can get it to add when checked but can not get it to reduce from the total when unchecked. In fact the code below adds every time the checkbox is checked or unchecked.
Please help
<html>
<body>
<?php
$testArray = [100000,200000,300000,144444,154444,16444,174444,18444];
?>
<div>
<?php for($i=0;$i<count($testArray);$i++) { ?>
<input type="checkbox" id = <?php echo $i ?> onclick="myFunction(<?php echo $testArray[$i] ?>)" value="<?php echo $testArray[$i] ?>" ><?php echo $testArray[$i] ?> <br/>
<?php } ?>
</div>
<table>
<tr style = "display: none;" >
<td></td>
<td id = 'balance'> 0 </td>
</tr>
<tr>
<td> Total : </td>
<td id = 'balance1'> 0 </td>
</tr>
</table>
<script>
// cumulative = 2
function myFunction(x){
balance = document.getElementById('balance').textContent;
total = parseInt(balance)
total = total + x
document.getElementById('balance').textContent = total
// display with number formated
total = total.toLocaleString("en-US");
document.getElementById('balance1').textContent = total
}
</script>
</body>
</html>
<?php for($i=0;$i<count($testArray);$i++) { ?>
<script>
if (document.getElementById("<?php echo $i ?>").checked === true) total += x;
</script>
<?php } ?>

Populate a row on a td on php javascript

i have this code:
<table id="table" style="width: 100%; text-align: center;" border="0">
<?php while ($row = $q->fetch()): ?>
<tr>
<th></th>
<th></th>
</tr>
<tr>
<td id="columna1">
<div class="col-lg-12" >
<div class="food-grid-item grid-style-one">
<br>
<br>
<div class="food-thumb grid-item">
<img src="assets/images/foodmenu/<?php echo $row['imagen']?>" href="#foodmenu1">
</div>
<div class="food-info grid-item">
<h3 class="food-title grid-item"><?php echo $row['product_name']?></h3>
<p><?php echo $row['descripcion']?></p>
<div class="food-price grid-item"><span>$</span><?php echo $row['price']?></div>
<div class="food-cart-tools grid-item">
Add to cart
</div>
</div>
</div>
</div>
</td>
<td id="columna2">
</td>
</tr>
<?php endwhile; ?>
</table>
as you can see, the "columna2" td, is empty cause i want to populate each database row on each to get the population in 2 columns and i don't know how to make it. it's something like this:
1 2
3 4
5 6
I try to do it on diferent ways but have no luck! Please if yo need more details please let me know i am new.
Thank you all
Start by putting all of the results in an array first.
$num = mysqli_num_rows($query);
$result_array = [];
for($i = 1; $i <= $num; $i++) {
$result = mysqli_fetch_array($query);
$result_array[] = $result;
}
And start to construct a table using a loop.
<table>
<thead>
<tr>
<th>| Column 1 |</th>
<th>| Column 2 |</th>
</tr>
</thead>
<tbody>
<?php
$column_size = 2;
for($row = 0; $row < $num / $column_size; $row++) {
echo '<tr>';
for($column = 0; $column < $column_size; $column++) {
echo '<td>';
echo 'ID: '.$result_array[($row * $column_size) + $column]['u_id'];
echo '</td>';
}
echo '</tr>';
}
?>
</tbody>
</table>
The result:
https://i.stack.imgur.com/CQSny.png

Adding array of value in javascript

I'm asking this question again and hope I get the answer this time, I have an array of number that adds and subtract on button click which works withonclick and a function created. I will like the sum up of the array 21998 and 11999 when this same button is click and will like to display the value in <p id=""sumTotal></p> find screenshot of what my array looks like:
I have an onClick function that multiple quantity with total every time - and + are clicked. I will like the sum-up of 21,998 and 11,999 when - and + are clicked. Below is what my HTML code and PHP script look like:
<p id = "sumTotal"></p>
<table class="table table-cart table-mobile">
<thead>
<tr>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<? for($i=0;$i<count($_SESSION['img_src']);$i++){ ?>
<tr>
<td class="price-col" id="<? echo $_SESSION['id'][$i].'_price' ?>" >₦<?php echo $_SESSION['price'][$i] ?></td>
<td>
<div onclick="clickMe(<?php echo $_SESSION['id'][$i]; ?>)">
<input type="number" value="1" min="1" max="10" step="1" data-decimals="0" required id = "<? echo $_SESSION['id'][$i].'_quantityCount' ?>">
</div><!-- End .cart-product-quantity -->
</td>
<td id = "<? echo $_SESSION['id'][$i].'_totalPrice' ?>">₦<?php echo $_SESSION['price'][$i] ?></td>
</tr>
<?
}
?>
<tbody>
</table>
And my javascript onclick looks like below code:
<script>
function clickMe(id) {
var price = document.getElementById(id+"_price").innerHTML;
let finalPrice = price.replace(/[^a-zA-Z0-9]/g, '')
var quantity = document.getElementById(id+"_quantityCount").value;
var totalPrice = quantity * finalPrice;
document.getElementById(id+"_totalPrice").innerHTML = "\u20A6"+totalPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
I will like to get the sum total of 21,998 and 11,999to <p id = "sumTotal"></p>
Call this function in the end of clickMe function.
function total() {
const priceElements = document.querySelectorAll('[id$="_totalPrice"]');
return [...priceElements].reduce((acc, curr) => acc + +curr.innerText, 0);
}
I was able to solve this myself, at first on the load of the page I sum up the all prices to get my initial sumTotal and did that in PHP with $subTotal_sum = array_sum( str_replace(",", "", $_SESSION['price']));. So <p id = "sumTotal"></p> will be <p id = "sumTotal">echo array_sum( str_replace(",", "", $_SESSION['price']));</p> And inside my javascript I made the changes with the script, I get the value of sumTotal subtracted it from Price and add the sumTotal and new price after + or - to get the new sumTotal below is my update code:
<p id = "sumTotal">$subTotal_sum = array_sum( str_replace(",", "", $_SESSION['price']));</p>
<table class="table table-cart table-mobile">
<thead>
<tr>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<? for($i=0;$i<count($_SESSION['img_src']);$i++){ ?>
<tr>
<td class="price-col" id="<? echo $_SESSION['id'][$i].'_price' ?>" >₦<?php echo $_SESSION['price'][$i] ?></td>
<td>
<div onclick="clickMe(<?php echo $_SESSION['id'][$i]; ?>)">
<input type="number" value="1" min="1" max="10" step="1" data-decimals="0" required id = "<? echo $_SESSION['id'][$i].'_quantityCount' ?>">
</div><!-- End .cart-product-quantity -->
</td>
<td id = "<? echo $_SESSION['id'][$i].'_totalPrice' ?>">₦<?php echo $_SESSION['price'][$i] ?></td>
</tr>
<?
}
?>
<tbody>
</table>
<script>
function clickMe(id) {
var sumTotal = document.getElementById("sumTotal").value;
var price = document.getElementById(id+"_price").innerHTML;
var initialSumTotal = parseInt(sumTotal) - parseInt(price);
let finalPrice = price.replace(/[^a-zA-Z0-9]/g, '')
var quantity = document.getElementById(id+"_quantityCount").value;
var totalPrice = quantity * finalPrice;
document.getElementById(id+"_totalPrice").innerHTML = "\u20A6"+totalPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
var sumTotal= parseInt(initialSumTotal)+parseInt(totalPrice);
// parsing the value to display on sub total
document.getElementById("sumTotal").value ="\u20A6"+sumTotal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>

Why I am not getting total value correctly after changing in item name?

I am new in Javascript. I have created an invoice table where the total value in the last column is calculated by selecting item price with putting the value in quantity field.
There are two issues being faced by me.
The total value is calculated correctly when I put the value in the quantity but total value isn't updating the correct total when I change item name.
The total value isn't reflecting, when I set the type of input i.e type="number" and try to add value by arrow
Here is the Code:
<div class="box pattern pattern-sandstone">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Item</th><th>Description</th><th>Price</th><th>Qty</th><th>Total</th>
</tr></thead>
<tbody id="customFields">
<tr>
<td>1</td><td >
<?php
$conn = mysqli_connect('localhost','dbuser','dbpass','dbname');
$query_order_to = "SELECT * from gs_items ORDER BY item_name ASC";
$result_order_to = $conn->query($query_order_to); ?>
<select name="selected_item" id="selected_item" onchange="myItemPrice()" data-placeholder="Item Name" >
<option value="">Select Item</option>
<?php
while($rows=mysqli_fetch_assoc($result_order_to))
{ ?> <option data-price='<?php echo $rows['price']; ?>' value='<?php echo $rows['Id']; ?>'> <?php echo $rows['item_name']; ?></option>";
<?php } ?> </select> </td>
<td ><textarea style="min-width: 90%;"></textarea></td>
<td > <input type="text" name="getprice" id="getprice" readonly></td>
<td ><input type="number" id="qty" onKeyUp="multiply()" input-number></td>
<td ><input type="text" id="total" readonly></td>
<td><button onclick="addRow();">Add</button></td>
</tr>
</tbody>
</table>
</div>
<script>
function findAddress(){
var address = $('#select_data').find(':selected').data('address');
$('#getcustomeraddress').val(address);
}
</script>
<script>
function myItemPrice(){
var price = $('#selected_item').find(':selected').data('price');
$('#getprice').val(price);
}
</script>
<?php
$conn = mysqli_connect('localhost','dbuser','dbpass','dbname');
function fill_unit_select_box($conn)
{
$query_item = "SELECT * from gs_items ORDER BY item_name ASC";
$result_item = $conn->query($query_item);
$x = 1;
foreach($result_item as $rows)
{ echo '<option data-prices="'.$rows['price'].'" value="'.$rows['Id'].'">'.$rows['item_name'].'</option>';
}
} ?>
<script>
function addRow()
{ var table = document.getElementById("customFields");
var i = 0;
while (i <= table.rows.length) {
i++;
}
i=i-1;
var html = '';
html += '<tr>';
html += '<td >'+i+'</td>';
html += '<td><select name="selected_items'+i+'" id="selected_items'+i+'" onchange="myItemPrices(' + i +')" data-placeholder="Item Name" ><option value="">Select Item</option>';
html += ' <?php echo fill_unit_select_box($conn); ?>
</select></td>';
html += '<td > <textarea style="min-width: 90%;"></textarea></td>';
html +='<td ><input type="text" disabled name="getprices'+i+'" style="font-size: 12px; color: #333333;" id="getprices'+i+'" ></td>';
html +='<td ><input type="number" ></td>';
html +='<td ><input type="number" ></td>';
html +='<td><button onclick="remove();">Remove</button></td>';
html +='</tr>';
$('#customFields').append(html);
}
function myItemPrices(var1){
i=var1;
var prices = $('#selected_items'+i+'').find(':selected').data('prices');
$('#getprices'+i+'').val(prices); }
</script>
<script>
function multiply() {
a = Number(document.getElementById('qty').value);
b = Number(document.getElementById('getprice').value);
c = a * b;
document.getElementById('total').value = c;
}
</script>
After several tries to find the solution, Finally I got the answer:
<script>
function myItemPrice(){
var price = $('#selected_item').find(':selected').data('price');
$('#getprice').val(price);
var getprice = document.getElementsByName('getprice')[0].value;
var qty = document.getElementsByName('qty')[0].value;
var total;
total = parseFloat(getprice) * parseFloat(qty);
document.getElementsByName('total')[0].value = total;
}
</script>

How to make input affect an echo

In this problem, when I sum a number to the quantity with the button,I want to change the total but it doesnt change, which is this line:
<td width="20%" class="Text-center"><?php echo number_format($producto['PRECIO']*$producto['CANTIDAD'],2); ?></td>
Here's the php code
<tr>
<td width="40%"><?php echo $producto['NOMBRE'] ?></td>
<td><button onclick="add_number()">mas</button><input type="text" id="suma" name="suma" value="<?php echo $producto['CANTIDAD'] ?>" readonly="readonly"></input></td>
<td width="20%" class="Text-center"><?php echo $producto['PRECIO'] ?></td>
<td width="20%" class="Text-center"><?php echo number_format($producto['PRECIO']*$producto['CANTIDAD'],2); ?></td>
<td width="5%">
<form action="" method="post">
<input type="hidden"
name="id"
value="<?php echo openssl_encrypt($producto['ID'],COD,KEY); ?>">
<button
class="btn btn-danger"
type="submit"
name="btnAccion"
value="Eliminar"
>Eliminar</button>
</form>
</td>
</tr>
Here's the Java code:
function add_number() {
var first_number = parseInt(document.getElementById("suma").value);
var result = first_number + 1;
document.getElementById("suma").value = result
}
In the function add_number where you increment the quantity value, you can also add the price to total cell of table each time, change your JavaScript function like this:
function add_number() {
var suma = parseInt(document.getElementById("suma").value); /* get current quantity */
var total = parseInt(document.getElementById("total").innerHTML); /* get current total */
var percio = parseInt(document.getElementById("percio").innerHTML); /* get price */
document.getElementById("suma").value = suma + 1; /* change quantity */
document.getElementById("total").innerHTML = (suma + percio).toFixed(2); /* change total */
}
Note the usage of innerHTML and value. The difference is because value is used for <input> tag while innerHTML is used for <td> tag.
Also note that you need to sed id for total cell and price cell in oder to read and write in them in your JavaScript function.
<td width="20%" class="Text-center" id="percio">
<?php echo $producto['PRECIO'] ?>
</td>
<td width="20%" class="Text-center" id="total">
<?php echo number_format($producto['PRECIO']*$producto['CANTIDAD'],2); ?>
</td>

Categories

Resources