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
Related
I'm a beginner seeking to solve this problem!
how to calculate the total of each item in the cart and how to calculate grand total?
this is my code
<td class="p-price first-row"><?php echo 'LBP '.number_format($r['product_price'],0)?>/KG</td>
<input type="hidden" class="unitprice" id="unitprice" value="<?php echo $r['product_price']?>">
<input type="text" id="quantity" class="quantity" value="<?php echo $weight ?>" readonly>
<td class="total-price first-row"><input class="total" id="total" readonly></td>
<input type="int" value="" id="grandtotal" class="grandtotal" readonly>
The variables you want arent quite clear. That said, it seems you're looking for something like:
$grandTotal = 0;
foreach ($_SESSION as $key => $values) {
if (strpos($key, "pid") !== false) {
$sql = "select * from products LEFT JOIN category on products.category_id = category.category_id where product_id = $_SESSION[$key]";
$result = $connect->query($sql);
$r = mysqli_fetch_assoc($result);
$w = "weight";
$w .= (string)$r['product_id'];
$weight = $_SESSION[$w];
$total = $r['product_price'] * $weight;
$grandTotal += $total;
}
}
I have problem, I want to calculate summation of height and weight after height is updated. The problem is after I click update, height is updated however weight will automatically change value to user_id (integer). So the summation will be bmi=height+id. Can you guys help solve my problem?
Below is PHP coding and form which I am using Bootstrap.
<!-- begin snippet: js hide: false -->
if(isset($_POST['updateH']))
{
$height = $_POST['height'];
$weight = $_SESSION['user'];
$bmi = $height + $weight;
$sql = "UPDATE users
SET
height = $height,
weight = $weight,
bmi = $bmi,
WHERE user_id=" . $_SESSION['user'];
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "<script type='text/javascript'>alert('Update Successfully!')</script>";
}
else
echo mysql_error();
}
<form method="post" role="form">
<h3> Height : <?php echo $userRow['height']; ?> cm</h3>
<input type="number" class="small" name="height" id="height" min="100" max="200" placeholder="Update Height CM"/>
<button type="submit" class="btn btn-warning" name="updateH"> UPDATE </button>
</form>
It seems like a format error in your sql statement
Use this
$sql = "UPDATE users SET height ='".$height."',weight ='".$weight."',bmi ='".$bmi."' WHERE user_id='".$_SESSION['user']."'";
If it is not updated for the above query
call mysql_commit(); after your mysql_query(); statement
Let me know if it is helpful
You don't have input field for Weight.
May be you are noticing it or maybe I'm wrong
Ok try this html code
<form method="post" role="form">
<h3> Height : <?php echo $userRow['height']; ?> cm</h3>
<input type="number" class="small" name="height" id="height" min="100" max="200" placeholder="Update Height CM"/>
<input type="number" class="small" name="weight" id="height" min="10" max="200" placeholder="Update Weight CM"/>
<button type="submit" class="btn btn-warning" name="updateH"> UPDATE </button>
</form>
And in javascript use the following
if(isset($_POST['updateH']))
{
$height = $_POST['height'];
$weight = $_POST['weight'];
$bmi = $height + $weight;
$sql = "UPDATE users SET height ='".$height."',weight ='".$weight."',bmi ='".$bmi."' WHERE user_id='".$_SESSION['user']."'";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "<script type='text/javascript'>alert('Update Successfully!')</script>";
}
else
echo mysql_error();
}
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);
});
});
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);
}
I am trying to build a web app in php something like stock maintenance, in my earlier page the user is allowed to insert the values of the bill which he gets from the dealer, as in from whom he buys the items which he sells from his shop, hence there he inserts details about the products bought, quantity, price per pc and the rest, i mean total price and the grand total is calculated using JS.
now there is another page where the user sets his profit percent on the grand total(Grand total= total price of the products + Transportation price) and i want the selling price of each item to calculated on its own, using a button.
the rest details are being fetched from the database.
the user sets the profit% on the grand total and now i have used the JS to calculate for each item.
<script type="text/javascript">
function poffy()
{
var d=document.getElementById("ui").value;
var e=document.getElementById("grt").value;
var p=parseFloat(d-e);
var t=document.getElementById("noit").value;
var e=p/parseFloat(t);
for(var b=0;b<parseFloat(t);b++)
{
var c=document.getElementById("costprice").value;
var y=new Array();
y[b]=c;
var f=document.getElementById("quant").value;
var mk=new Array();
mk[b]=f;
var g=e/parseFloat(mk[b]);
var h=g + parseFloat(y[b]);
document.getElementById("sellprice").value=h;
}
}
</script>
Now The problem is that the calculated value is being displayed only once and only for the first item ,not for the other rows.
My php code:
<?php
include("connect.php");
$wer='ccat';
$i=0;
$dater=date("D/M/Y");
$sq="SELECT D_id FROM dealerdetail where Dealer='$wer'";
$res=mysql_query($sq);
while($row=mysql_fetch_array($res))
{
$did=$row["D_id"];
}
$io="Select pdate,tranprice,grandtotal from dateprice where D_id='$did'";
$qw=mysql_query($io);
while($row=mysql_fetch_array($qw))
{
$pd=$row["pdate"];
$as=$row["tranprice"];
$as=0 + $as;
$tr=$row["grandtotal"];
$tr=0 + $tr;
$sql="Select * from additem where Ditem_id='$did'";
$result = mysql_query($sql);
while($pop=mysql_fetch_array($result))
{
$b= $pop["Product"];
$c= $pop["Brand"];
$d= $pop["Model"];
$e= $pop["Dprice"];
$f= $pop["Quantity"];
$t=$e*$f;
$g= $pop["Quality"];
echo "<tr>";
echo "<td> $wer</td>";
echo "<td> $b </td>";
echo "<td> $c </td>";
echo "<td> $d </td>";
echo "<td><input type=text name=costprice id=costprice onkeyup=sell(); class=price value=$e /></td>";
echo "<td><input type=text name=quantity[] class=quantity id=quant value=$f /></td> ";
echo "<td><input name=txt type=text class=txt value=$t readonly /></td> ";
echo "<td><input type=text name=sellprice id=sellprice /></td>" ;
echo "<td> <div align=center ><p>$g<p></div> </td>";
/*echo "<td><input type=text name=purchasedt value=$pd /></td> "; */
echo "<td><input type=text name=current value=$dater /></td>
</tr>";
$i++;
/* if(isset($_POST['S.P']))
{
$po=$_POST['grandy'];
$ap=$po-$tr;
$ao=$ap/$i;
$ai=$ao/$f;
$ul=$_POST['costprice'];
$re=$ai + $ul;
echo $re;
}
*/
}
}
echo "<label>Number Of Items : </label> <input type=text name=no size=6 id=noit value= $i> ";
echo " <label>Dealer Name :</label> <input type=text name=fetch id=fetc readonly />";
echo " <label>Purchase Date :</label> <input name=prdt type=text size=10 class=pur value=$pd readonly /> <br><br> ";
?>
</table>
<?php
echo "<br><br><label> Transport Price :</label><input type = text name=transport value=$as > <br>";
echo " <br><label> Grand Total : </label> <input type = text name=grandy id=grt value=$tr > ";
?>
<br >
<br >
<input type="button" name="proft" onclick="calcu();" value="Profit" />
<input type ="text" name="grandy" id="ui" />
I see you already have a variable $i that you're incrementing on every row, you can use that to make the IDs unique:
echo "<td><input type=text name=costprice id=costprice$i onkeyup=sell(); class=price value=$e /></td>";
echo "<td><input type=text name=quantity[] class=quantity id=quant$i value=$f /></td> ";
echo "<td><input name=txt type=text class=txt value=$t readonly /></td> ";
echo "<td><input type=text name=sellprice id=sellprice$i /></td>" ;
Then change your Javascript to take a parameter that specifies the row:
function poffy(i)
{
var d=document.getElementById("ui").value;
var e=document.getElementById("grt").value;
var p=parseFloat(d-e);
var t=document.getElementById("noit").value;
var e=p/parseFloat(t);
for(var b=0;b<parseFloat(t);b++)
{
var c=document.getElementById("costprice"+i).value;
var y=new Array();
y[b]=c;
var f=document.getElementById("quant"+i).value;
var mk=new Array();
mk[b]=f;
var g=e/parseFloat(mk[b]);
var h=g + parseFloat(y[b]);
document.getElementById("sellprice"+i).value=h;
}
}
I don't see where in your HTML you call the poffy() function. You need to change that code to pass the row number as a parameter.
I noticed another problem in your code. You have the following at the bottom of the table:
echo "<label>Number Of Items : </label> <input type=text name=no size=6 id=noit value= $i> ";
echo " <label>Dealer Name :</label> <input type=text name=fetch id=fetc readonly />";
echo " <label>Purchase Date :</label> <input name=prdt type=text size=10 class=pur value=$pd readonly /> <br><br> ";
Everything in a <table> has to be inside <tr> and <td> or <th> elements. You either need to put those wrappers around this line, or move them out of the table.