How to calculate total price of multiple items in cart? - javascript

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

Related

Calculating final total after taking store credit into account

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

Jquery insert value into input with php dynamic name

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.

Javascript calculate subtotal and total from mysql

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

Javascript Auto Sum dynamic textboxes

I am creating a quote/order page that includes different types of options for the order all of which are calculated differently. I have a javascript function that will take the values inputed into the text boxes onchange and add a total at the bottom of a page. The issue I'm running into is the base product can be multiple lengths and many option prices are calculated by the foot. So what I have done is made a hidden field that stores the length of the base product and drop down menus to select the option. I have another javascript function that multiplies these two values and puts the total in one of the text boxes that should be auto summed with the first function. Both work perfectly independent of each other, however the issue I have is that the "on change command for the sum function isn't being recognized when the multiplication function auto updates the text box...
Any Help is very greatly appreciated.
Code...
<script type="text/javascript">
function multiplyLengthWalls(){
var length = parseInt(document.getElementById('length').value, 10);
var walls = parseInt(document.getElementById('walls').value, 10);
var total = length*walls;
document.getElementById('wallstotal').value = total;
}
</script>
<script type="text/javascript">
function sumCost() {
var arr = document.getElementsByName('featuretotal');
var tot = 0;
for(var i=0; i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('totalcost').value = tot;
}
</script>
HTML....
<td><select name="walls" id="walls" onchange="multiplyLengthWalls()">
<?php
do {
?>
<option value="<?php echo $row_walls['dcost']?>"><?php echo $row_walls['name']?></option>
<?php
} while ($row_walls = mysql_fetch_assoc($walls));
$rows = mysql_num_rows($walls);
if($rows > 0) {
mysql_data_seek($walls, 0);
$row_walls = mysql_fetch_assoc($walls);
}
?>
</select></td>
<td><label for="wallstotal"></label>
<input type="text" name="featuretotal" id="wallstotal" class="test" onchange="sumCost()"/></td>
</tr>
<tr>
<td>Ceiling:</td>
<td><label for="ceiling"></label>
<select name="ceiling" id="ceiling">
<?php
do {
?>
<option value="<?php echo $row_ceiling['dcost']?>"><?php echo $row_ceiling['name']?></option>
<?php
} while ($row_ceiling = mysql_fetch_assoc($ceiling));
$rows = mysql_num_rows($ceiling);
if($rows > 0) {
mysql_data_seek($ceiling, 0);
$row_ceiling = mysql_fetch_assoc($ceiling);
}
?>
</select></td>
<td><label for="ceilingtotal"></label>
<input type="text" name="featuretotal" id="ceilingtotal" class="test" onchange="sumCost()"/></td>
</tr>
<tr>
<td>Floor:</td>
<td><label for="floor"></label>
<select name="floor" id="floor">
<?php
do {
?>
<option value="<?php echo $row_floor['dcost']?>"><?php echo $row_floor['name']?></option>
<?php
} while ($row_floor = mysql_fetch_assoc($floor));
$rows = mysql_num_rows($floor);
if($rows > 0) {
mysql_data_seek($floor, 0);
$row_floor = mysql_fetch_assoc($floor);
}
?>
</select></td>
<td><label for="floortotal"></label>
<input type="text" name="featuretotal" id="floortotal" class="test" onchange="sumCost()"/></td>
</tr>
</table>
<p> </p>
</div>
<div id="structural">structural</div>
<div id="hidden">hidden --
<input name="length" type="hidden" id="length" value="<?php echo $row_models['length']; ?>" />
</div>
</div>
<div id="footer">
<div id="total">total:<input name="totalcost" type="text" id="totalcost" readonly="readonly" /></div>

Ajax oncheck event to search item in a table

modify search
<div class="highlight_2"> <img src="images/collapse2.jpg" width="151" height="28" border="0" />
<div id="inox">
<input type="checkbox" value="kar_kar" />kar and kar <br />
<input type="checkbox" value="bala_bala" />bala and bala <br />
<input type="checkbox" value="jena_jena" />jena and jena <br />
<input type="checkbox" value="senapati" />senapati <br />
<input type="checkbox" value="sarangi_sarangi" />sarangi and sarangi <br />
<input type="checkbox" value="sairam" />sairam <br />
<input type="checkbox" value="madhumita" />madhumita <br />
<div class="clear"></div>
</div>
search table
<tr>
<td>Sl No.</td>
<td>Bus Operator</td>
<td>Bus No. </td>
<td>Departure Time</td>
<td>Arrival time</td>
</tr>
<?php
$count=0;
$s=mysql_query("SELECT * FROM bus_detail where source_point='$_SESSION[source_point]' && destination_point='$_SESSION[destination]'");
while($row=mysql_fetch_array($s))
{
$count+=1;
?>
<tr>
<td><?php echo $count; ?></td>
<td><input name="bus_name" type="text" value="<?php echo $row['bus_name'];?>" class="input_box" /> </td>
<td><?php echo $row['bus_no'];?></td>
<td><?php echo $row['departure_time'];?></td>
<td><?php echo $row['arrival_time'];?></td>
</tr>
<?php }?>
I want to use my modify search in a ajax oncheck event.. In the picture i ve given ,this is my search list apper but if i check a check box name "jena and jena" from the bus operator div, it should only show me the result of jena and jena , the other two, i want to hide them .. I want to modify my search according to my bus operators(after checking a check box from the operator list).. It ll be a great help .. Thank you
My database :
Sorry i miss understood your question. I think you are looking to hide / show html table rows when user selects list. If this is what you are look, Then please check by code below.
Note: You can tweak this code to get better performance and result
Fiddle: http://jsfiddle.net/663Mx/2/
$("#inox input[type='checkbox']").live('click', function () {
// STORE CHECKED VALUED IN ARRAY
var cv = [];
$("#inox input[type='checkbox']:checked").each(function () {
cv.push($(this).val());
});
// SHOW / HIDE ROWS BY DEFAULT
if(cv.length <= 0) {
$("#mytab tbody").find("tr").show();
} else {
$("#mytab tbody").find("tr").hide();
var rows = $("#mytab tbody").find("tr");
var data = $(this).val();
// LOOP THROUGH AND SHOW ONLY CHECKED ROWS
rows.each(function (i, v) {
for (var n=0; n<cv.length; n++) {
var check = $(v).find('td').filter(":contains('" + cv[n] + "')");
check.parent('tr').show();
}
});
}
});

Categories