Adding array of value in javascript - 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>

Related

Onchange event is not detecting copy paste in input fields

I have so many Input fields in html table and I am using the code below to copy paste columns from excel directly to these input fields. and the code below is working great for copy paste columns from excel to this html input table fields. My problem is that I want onchange event for each input to detect when I copy paste and alert these values. cause then I can take each value was changed and change it in the database. The Onchange event does not detect change in value when I copy paste!
<table>
<thead>
<tr>
<th>Name</th>
<th>Unit</th>
<th >ID</th>
<th >Margin </th>
</tr>
<tbody>
<?php
$query = " select name,unit,Margin, id FROM Table1";
$stmt = $conn->query( $query );
$count=0;
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) )
{ ?>
<tr>
<td> <input onchange="send(this)" type="text" value="<?php echo $row['Name']; ?>"> </td>
<td><input onchange="send(this)" type="number" value="<?php echo $row['unit]; ?>" ></td>
<td><input type="number" value="<?php echo $row['ID']; ?>" ></td>
<td><input onchange="send(this)" type="number" value="<?php echo $row['Margin']; ?>" ></td>
</tr>
<?php } ?>
</tbody>
</thead>
</table>
<!-- Copy Paste in input fields -->
<script type="text/javascript">
$('input').on('paste', function(e){
var $this = $(this);
$.each(e.originalEvent.clipboardData.items, function(i, v){
if (v.type === 'text/plain'){
v.getAsString(function(text){
var x = $this.closest('td').index(),
y = $this.closest('tr').index()+1,
obj = {};
text = text.trim('\r\n');
$.each(text.split('\r\n'), function(i2, v2){
$.each(v2.split('\t'), function(i3, v3){
var row = y+i2, col = x+i3;
obj['cell-'+row+'-'+col] = v3;
$this.closest('table').find('tr:eq('+row+') td:eq('+col+') input').val(v3);
});
});
});
}
});
return false;
});
</script>
<script>
function send(value){
alert(value.value);
}
</script
I use this for my input for cut ,copy & paste
function send(value){
alert(value.value);
}
input here : <input onchange="send(this)" type="text" oncopy="send(this)" onpaste="send(this)" oncut="send(this)" type="text" value=""/>

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 } ?>

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>

Javascript is not doing sum of all records

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>

Changing value in html table dynamically

I have an html table where i retrieve data from a database using PHP. The table is quite simple, i have three fields: Name, Quantity and Price. At the end of the table i have an additional field, Subtot, that shows the final cost (SumOfAllItems(Quantity*Price)).
I need to be able to change the "Quantity" value in each row and the "Subtot" should update accordingly. I also need to be able to set min/max value the user can use to update the cell.
I was thinking to add something like a button or any kind of list/input by the "Quantity" value in each row.
I think i need to use javascript but i am not sure, any suggestion is welcome.
Following my code.
Thanks
<table>
<tbody>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price<th>
</tr>
<?php
while($row2 = $result->fetch_assoc())
{?>
<tr>
<td><?php echo $row2["Name"] ?></td>
<td><?php echo $row2["Quantity"] ?></td>
<td><?php echo $row2["Price"]?></td>
</tr>
<?php
$subtot = $subtot + ($row2["Price"] * $row2["Quantity"])
} ?>
<td></td>
<td><b>Subtot.</b></td>
<td><b><?php echo $subtot2 ." Euro"; $tot = $subtot1 + $subtot2;?> </b></td>
</tbody>
</table>
The following should work, however i do not recommend this method (any method btw) without any validation on server side.
You need this on top of your php file:
<?php
$total = 0;
Then your table like:
<table>
<thead>
<tr>
<th>Name</th>
<th>Quantity</th>
<th>Price<th>
</tr>
</thead>
<tbody>
<?php while($row2 = $result->fetch_assoc()) { ?>
<tr>
<td><?php echo $row2['name'] ?></td>
<td><input class="row" min="0" onchange="myFunction()" data-price="<?php echo $row2['price'] ?>" type="number" value="<?php echo $row2['quantity'] ?>"/></td>
<td><?php echo $row2['price'] ?></td>
</tr>
<?php
$total += $row2['price'] * $row2['quantity'];
}
?>
<td></td>
<td>
<b>Subtot.</b>
</td>
<td>
<b id="total"><?php echo $total; ?></b>
</td>
</tbody>
</table>
And you need the following script tag:
<script>
function myFunction(){
var total = 0;
var elements = document.getElementsByClassName("row");
for(var i = 0; i < elements.length; i++) {
total += elements[i].value * elements[i].dataset.price;
}
var totalEl = document.getElementById("total");
totalEl.innerHTML = total;
}
</script>
Again.. this is a very simple solution, but it should work.

Categories

Resources