First of all, I'm sorry if this question has already been asked and solved before, but I cant find the exact answer/solution for my problem.
My question is, how do I calculate grand-total if a user changes quantity and/or selects more that 1 product? My product item list and value is from mysql.
Here's my form details:
<?php $price = 10.00;?>
<input name="qty_<?php echo $obj->product_code;?>" type="text" id="qty<?php echo $obj->product_code;?>" value="0" size="2" onkeyup="calculate()">
<input name="subtotal_<?php echo $obj->product_code;?>" type="text" id="subtotal_<?php echo $obj->product_code;?>" value="0.00" size="7" readonly>
<input name="qty_<?php echo $obj->product_code;?>" type="text" id="qty<?php echo $obj->product_code;?>" value="0" size="2" onkeyup="calculate()">
<input name="subtotal_<?php echo $obj->product_code;?>" type="text" id="subtotal_<?php echo $obj->product_code;?>" value="0.00" size="7" readonly>
<input name="grandtotal" type="text" id="grandtotal" value="0.00" readonly>
I'm using my php/mysql results value for my input field name/id, as it's easier for me to identify/pass the value when submitted.
Here's my Javascript:
function calculate()
{
var quantity = document.getElementById('<?php echo $obj->product_code;?>').value;
var currprice = <?php echo $obj->product_code.$obj->product_price;?>;
var total = quantity * currprice;
document.getElementById('subtotal_<?php echo $obj->product_code;?>').value = total.formatMoney(2,',','.');
}
So, how do I calculate the subtotal from each product and display it at grand total text field?
I've already searched Google but have not been able to solve my problem.
1) Using the right ID's
The id's of the quantity fields do not match with the getElementById in the function. It should start with "qty_", not directly the product code. Also, for the sake of regularity, change the id's in the <input>'s from "qty" to "qty_".
2) The right structure
The html you use now, has double quantity and subtotal <input> fields with the same ID. This causes Javascript to be unable to access these values. Make sure you distinguish between the names and ID's of these input fields.
PHP:
$products = array(
array("price"=>10, "code"=>"product1"),
array("price"=>25, "code"=>"product2")
);
foreach($products as $key => $productInfo) {
/* echo a hidden field with the price per product (for calculation later) */
echo '<input type="hidden" name="price_'. $productInfo["code"] .'" id="price_'. $productInfo["code"] .'" value="'. $productInfo["price"] .'" />';
/* echo the quantity field for this product */
echo '<input class="qty" name="'. $productInfo["code"] .'" id="'. $productInfo["code"] .'" type="text" value="0" size="2" onkeyup="calculate()">';
/* echo the subtotal field for this product */
echo '<input name="sub_'. $productInfo["code"] .'" type="text" id="sub_'. $productInfo["code"] .'" value="0.00" size="7" readonly>';
}
/* echo the field for total price */
echo '<input type="text" name="total" id="total" value="0.00" />';
This results in sets of three input fields per product:
One for the price per product (id="price_THEPRODUCTCODE")
One for the quantity (id="THEPRODUCTCODE")
And one for the subtotal (id="sub_THEPRODUCTCODE")
Javascript
I suggest using the jQuery library for faster and easier collection of the data from the input fields here.
The function would then be:
function calculate() {
var total = 0;
// for each quantity field:
$("input.qty").each(function() {
// get product code
var productCode = $(this).attr("id");
// get price per product
var price = $("#price_"+productCode).val();
// get quantity
var quantity = $(this).val();
// calculate subtotal
var subtotal = (price*quantity);
// put new subtotal back in the input field
$("#sub_"+productCode).val(subtotal);
// add subtotal to total
total += subtotal;
});
// put total in the input field of total
$("#total").val(total);
}
Related
So I've done my order form differently now and I'm trying to calculate the final total based on how much store credit a user has. So for example if they had £100 credit and the total comes to £50 then it would just take away £50 from the total and then the user would be left with £50 credit. Then as well if the total came to £500 then taking into account the user's credit the total would come to £400 and the user would be left with £0 credit.
The final total is priced by taking the user's store credit into account
I'm having some difficulty calculating the final total, so this is my order form at the moment:
<form action='' method='post' align = "center">
<h2>Purchase</h2>
<p>Return to website</p>
<p><label>Name</label><br />
<input type='text' name='name' required ></p>
<p><label>Email</label><br />
<input type='text' name='email' required ></p>
<p><label>Number</label><br />
<input type='text' name='number' required ></p>
<p><label>Address</label><br />
<input type='text' name='address' required ></p>
<p><label>Town</label><br />
<input type='text' name='town' required ></p>
<p><label>Postcode</label><br />
<input type='text' name='postcode' required ></p>
<p><label>County</label><br />
<input type='text' name='county' ></p>
<p><label>Product</label><br />
<input type='text' name='product' readonly value='<?php echo $row['product'];?>'></p>
<p><label>Price</label><br />
<input type='text' name='price' readonly value='<?php echo $row['price'];?>'></p>
<p><label>Amount</label><br />
<input type="text" id="amount" name="amount" oninput="calc()" onkeypress="return isNumber(event)" />
<p>Price : <b>£<span name="totalPrice" id="totalPrice" size="8"></span></b></p>
<input type ="text" value="" name="shopTotal" id="shopTotal" />
<input type="text" value="" id="minusCredit" name="minusCredit"/>
<p>Delivery is £4.99</p>
<p><input type='submit' name='submit' value='Submit Order'></p>
and this is the script I have in place at the moment to try calculate the final total:
<script>
function calc()
{
var amount = document.getElementById("amount").value;
<?php
//calculate the discount
$price = $row['price'];
$deliv = 4.99;
$money = $_SESSION['money'];
if ($money > $price) {
$discount = $price;
} else {
$discount = 0;
}
echo $discount;
?>
//calculate final cost
var totalBefore = <?php echo $price ?> * amount + <?php echo $deliv?>
var discount = <?php echo $discount ?> * amount + <?php echo $deliv?>
var totalAfter = <?php echo $price ?> * amount + <?php echo $deliv?> - discount
document.getElementById("totalPrice").innerHTML = totalAfter.toFixed(2)
document.getElementById("shopTotal").value = totalAfter.toFixed(2)
document.getElementById("minusCredit").value = discount.toFixed(2)
}
</script>
The issue with this is that no matter what the total comes to it, the discount will always take it to £0 no matter how much store credit the user has.
The amount of store credit they have is based on this value:
$money = $_SESSION['money'];
The issue with I just to $discount = $money - $price; is that if the total was only £10 and the user had store credit then $discount would then equal £90 so the final total would become £80.
What I'm trying to do is something like if the $money variable is greater than the price + delivery then the final would just be 0 and then I would update the database table to take away from the user's store credit. Or if the the price + delivery total is greater than the $money variable then final total would be the price + deliver minus the store credit the user has.
I'm hoping this now makes sense
How can I fix this?
Okay so after playing about with it I've managed to get it to work. Might not be the most elegant solution but it works.
My calculation script is now like so:
function calc()
{
var amount = document.getElementById("amount").value;
<?php
//calculate the discount
$price = $row['price'];
$deliv = 4.99;
$money = $_SESSION['money'];
$discountTotal = $money - $price;
$discount = min($discountTotal, $price);
echo $discount;
?>
//calculate final cost
var totalBefore = <?php echo $price ?> * amount + <?php echo $deliv?>
var discount;
var totalAfter;
if (totalBefore < <?php echo $money ?>) {
discount = <?php echo $discount ?> * amount + <?php echo $deliv?>;
}
if (totalBefore > <?php echo $money?>) {
var discountCalculate = <?php echo $price ?> * amount + <?php echo $deliv - $money?> ;
discount = totalBefore - discountCalculate;
}
var totalAfter = <?php echo $price ?> * amount + <?php echo $deliv?> - discount
document.getElementById("totalPrice").innerHTML = totalAfter.toFixed(2)
document.getElementById("shopTotal").value = totalAfter.toFixed(2)
document.getElementById("minusCredit").value = discount.toFixed(2)
}
</script>
The script checks to see if total before before taking into account store credit is bigger or less than the amount of store credit the user has.
If it is less then the total will be 0 and the amount taken off will be whatever the price was.
If it is more then the script will first calculate how much the total would be from the total before - the amount of store credit the user has.
The discount value is now the total before price - the value just calculated
Hello, Im trying to calculate cart total using JavaScript but it is showing the total for the first item only! Any help please?
This is my JS Code
<script>
function f(){
var price = $('#unitprice').val();
var quantity = $('#quantity').val();
total = price*quantity;
$('#total').val(total);
return;
};
</script>
HTML PHP
<td class="p-price first-row"><?php echo 'LBP '.number_format($r['product_price'],0)?>/KG</td>
<input type="hidden" id="unitprice" value="<?php echo $r['product_price']?>" onload="f();">
<input type="text" id="quantity" value="<?php echo $weight ?>" readonly onload="f();">
<td class="total-price first-row"><input id="total" readonly style="border:none; color:#e7ab3c; text-align:center; font-weight: bold;"></td>
This is my work, check the image please!
Any idea how to work it out?
Grand total solution will be appreciated also! Thank you
can you help for quantity input box on featured products , opencart 2.3.0.2
<input type="text" size="3" id="quantity-<?php echo $product['product_id']; ?>" name="quantity" value="1" placeholder="1" class="form-control my-form-control input-lg qty-input radius-none pull-left" />
this code will show input box and default 1 and it adds 1 products to cart but I need any numbers to be added to cart.
You should change the value attribute. Like value="<?php echo $needed_quantity; ?>"
Or delete value attribute but than you need to check if user set the quantity (check if empty) and inform user that he must set the quantity manually
I have a php generated form with fields retrieved from DB and I want to do in time calculations before save again in DB. Im retrieving all values from inputs and the sum is working, but Im not able to insert the sum result into a inputbox(it doesnt have to be necessarily a inputbox).
What im doing wrong?
Inside a php while I have the fields:
<td><input type="text" onkeyup="calculate(<?php echo($row["usr_id"]);?>)" class="valor_<?php echo($row["usr_id"]);?>" title="Valor Pago" style="font-size:18px; text-align:center;" value="<?php echo(formata_moeda($row["pedprod_valorpago"]));?>" name="<?php echo($row["usr_id"]);?>" id="<?php echo($row["prod_id"]);?>" /></td>
The TOTAL input is like this
<th><input type="text" class="totalpago_<?php echo($row["usr_id"]); ?>" name="totalpago_<?php echo($row["usr_id"]); ?>" id="totalpago_<?php echo($row["usr_id"]); ?>" value="<? echo(formata_moeda($total_valorpago_cestante)); ?>" disabled="disabled"></th>
And the javascript function
function calculate(usrId) {
var total = 0;
var totalusr = 0;
$("input.valor_"+usrId).each(function() {
var price = parseFloat($(this).val().replace(',','.'));
totalusr += price;
//window.alert("Usuario: "+ usrId +" - Valor: "+ price);
});
$("input.totalpago_"+usrId).val(totalusr);
window.alert($("input.totalpago_"+usrId).val());
}
This alerts are just to test proposes.
I have 12 of these forms on a page on each product. It allows someone to enter a quantity and have it calculate the price, but doesn't yet work. The new price should replace what's in the orderprice class div.
<form action="" method="post">
<input type="number" id="amount-<?php echo $productId; ?>" class="orderamount" name="amount" value="1" min="1" max="2000" maxlength="4" />
<input type="hidden" name="product" value="<?php echo $productId; ?>" readonly="readonly" disabled="disabled" />
<div id="price-<?php echo $productId; ?>" class="orderprice">
<?php
echo html_entity_decode($currencyAlignCode) . round($productPrice * $currencyMultiplier, 2);
?>
</div>
<input type="submit" class="addcart" value="" name="order" />
</form>
I want to take the value of amount-<?php echo $productId; ?>, and automatically calculate the price by multiplying that value by $productPrice and again by $currencyMultiplier, and then add html_entity_decode($currencyAlignCode) in front of it.
I know how to do that if there were only 1 form on the page and I didn't need to account for <?php echo $productId; ?>. This is how I would do it for an individual form, but how can I do it for several? And each price would only grab the quantity from the associated input box?
$(document).ready(function() {
$("#amount").bind('click keyup', function(event) {
var amount = $("#amount").val();
var productPrice = <?php echo $productPrice; ?>;
var currencyMultiplier = <?php echo $currencyMultiplier; ?>;
var currencyCode = <?php echo html_entity_decode($currencyAlignCode); ?>;
var totalPrice = amount * productPrice * currencyMultiplier;
$("#price").html('currencyCode' + totalPrice);
});
});
This code will only do it for 1 product. I want the input from each to show in the respective price box.
Sorry if it's not clear, it was kind of hard to explain.
Maybe something like this? Use multiple selectors or grab the selectors that start with something.
<input type="number" id="amount-<?php echo $productId; ?>" productPrice="<?php echo $productPrice; ?>" ...
$("[id^=amount]").each(function(index){
$(this).bind("click key up", function(){
var amount = $(this).val();
var productPrice = $(this).attr('productPrice');
...
});
});
https://api.jquery.com/each/
http://api.jquery.com/attribute-starts-with-selector/
I ended up doing some extensive Googling and coming up with the solution.
I use attr to grab the id based on the changed class.
$(document).ready(function() {
$(".orderamount").bind('click keyup', function(event) {
var productId = $(this).attr('id');
var setId = productId.substring(7);
var amount = $('#amount-' + setId).val();
var productPrice = <?php echo $productPrice; ?>;
var currencyMultiplier = <?php echo $currencyMultiplier; ?>;
var currencyCode = <?php echo html_entity_decode($currencyAlignCode); ?>;
var totalPrice = round(amount * productPrice * currencyMultiplier, 2);
$('#price-' + setId).html('currencyCode' + totalPrice);
});
});