Jquery insert value into input with php dynamic name - javascript

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.

Related

How to calculate total price of multiple items in cart?

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

Auto add checkbox values and keep their name for storing in database

I have checkboxes retrieved from my database with respective item_name and value which happen to be displayed correctly, but the values are being added/subtracted automatically when selected/checked. However, i want to save the selected check box item_names and also the total sum of the values from the checkboxes. I can't accomplish this because the value option holds numeric data which should have been the checkbox item_name; here is so far what i have.
<script type="text/javascript">
function checkTotal() {
document.listForm.total.value = '';
var sum = 0;
for (i=0;i<document.listForm.sel_car.length;i++) {
if (document.listForm.sel_car[i].checked) {
sum = sum + parseInt(document.listForm.sel_ca[i].value);
}
}
document.listForm.total.value = sum;
}
</script>
HTML/PHP Snippet
<h4>Available Cars | Click on desired car(Multiple Selections enabled) | Total Price: <input type="text" size="2" name="total" value="0"/></h4>
<div class="form-group">
<?php
$stmt = $DB_con->prepare('SELECT * FROM cars ORDER BY car_id DESC');
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
<div class="col-md-3"><label class="btn btn-primary">
<img src="user_images/<?php echo $row['userPic']; ?>" alt="..." class="img-thumbnail img-check"><input type="checkbox" name="sel_car[]" id="item4" value="<?php echo $row['car_price']; ?>" class="hidden" autocomplete="off" onchange="checkTotal()"/>
<h5><?php echo $row['se_car_model']; ?> | UGX <?php echo $row['car_price']; ?>/=</h5>
</label></div>
<?php
}
}
?>
You should also retrieve id along with Item name and value and assign the id to the checkbox.
Add the hidden field in the form
<input type="hidden" name="itemsArr" id="itemsArr" value="">
checkbox
<input onclick="checkTotal(this)" type="checkbox" id="itemId" name="ItemName" value="ItemPrice">
Div showing total amount
<div id="totalDiv"></div>
script
<script type="text/javascript">
var arr = [];
var total = 0;
function checkTotal($this)
{
var varId= $this.id;
if ($($this).is(":checked")) {
arr.push(varId);
}
else
{
arr.splice( $.inArray(varId,arr) ,1 );
}
$("#itemsArr").val(arr);
// get the price of the item from the controller by passing id to controller
$.ajax({
type: 'POST',
url: BASE_URL+"controllerName/methodName",
data: {'id':varId},
success: function (data) {
data = JSON.parse(data);
total += data.price;
$("#totalDiv").html(total);
}
});
}
On sumbitting the form you will be getting the hidden value and then store it in the database
When you want to retrieve the value from the database you can get the field and convert that string into an array using explode function and do the further tasks.

ajax code not taking the data from table to second row

hi guys i have an issue on ajax. where ajax can't work to take the data of second rows.
This's code in model
function getdtbarang($barcode = FALSE) {
if ($barcode === FALSE)
{
$query = $this->db1->get('tblmstbarang');
return $query->result_array();
}
$query = $this->db1->get_where('tblmstbarang', array('barcode' => $barcode));
return $query->row_array();
}
This's code in controller:
function getdatabarang() {
$barcode = $this->input->post('barcode');
$data=$this->Mbarang->getdtbarang($barcode);
echo json_encode($data);
}
This's ajax code in view. NB:some code has updated
<script type="text/javascript">
function getdatabrg(barcode){
$('#barcode_2').each(function() {
var barcode =$('#barcode_2').val();
$.ajax({
type : "post",
data : "barcode=" +barcode,
url : "<?php echo base_url();?>index.php/master/barang/Cbarang/getdatabarang",
dataType:"json",
success: function(data){
for(var i in data)
{
var obj= data[i];
$("#barang_nama_2").val(obj.barang_nama);
$("#harga_beli_2").val(obj.harga_beli);
}}
});
});
}
$(document).ready(function() {
$('#barcode_2').keyup(function() {
getdatabrg();
});
});
</script>
<td><input type="text" class="form-control" id="barcode" name="barcode[]" value="<?php echo set_value('barcode['.$i.']') ;?>" onKeyUp="getValues()" ></td>
<td><input type="text" class="form-control" id="barang_nama" name="barang_nama[]" value="<?php echo set_value('barang_nama['.$i.']') ;?>" onKeyUp="getValues()" disabled></td>
<td><input type="text" class="form-control" id="harga_beli" name="harga_beli[]" value="<?php echo set_value('harga_beli['.$i.']');?>" onKeyUp="getValues()" disabled></td>
<td><input type="text" class="form-control" id="barcode_2" name="barcode[]" value="<?php $a=set_value('barcode[0]') ; echo $a;?>"></td>
<td><input type="text" class="form-control" id="barang_nama_2" name="barang_nama[]" value="<?php $a=set_value('barang_nama[0]') ; echo $a;?>" onKeyUp="getValues()" readonly></td>
<td><input type="text" class="form-control" id="harga_beli_2" name="harga_beli[]" value="<?php $a=set_value('harga_beli[0]'); echo $a;?>" onKeyUp="getValues()" readonly></td>
<td><input type="text" class="form-control" id="barcode_3" name="barcode[]" value="<?php echo $detail->barcode;?>"></td>
<td><input type="text" class="form-control" id="barang_nama_3" name="barang_nama[]" value="<?php echo $detail->barang_nama;?>" onKeyUp="getValues()" readonly></td>
<td><input type="text" class="form-control" id="harga_beli_3" name="harga_beli[]" value="<?php echo $detail->harga_beli;?>" onKeyUp="getValues()" readonly></td>
i hope getting solve for this problem. many thanks for all your response.
Like Zerfiryn mentioned : "You cannot use the same id for html elements. jQuery will only fetch the first element"
solutions: you can use the same class multiple times on html elements. Call not the id in your ajax but the class form-control.
So, replace $("#barcode") with $(".form-control")
writing an answer cause I can't place comments -.-
You have not constructed model correctly your model is directly outputting the data which so you will end up with the output something like
[{barang_name:"value"},{harga_beli:"value"}][{barang_name:"value"},{harga_beli:"value"}][{barang_name:"value"},{harga_beli:"value"}]...
which is not correct JSON
your should output correct JSON your output should be
[ [{barang_name:"value"},{harga_beli:"value"}], [{barang_name:"value"},{harga_beli:"value"}],.. ]
which is array of arrays
The simplest way to achieve this is
1 ) get the desired data from your model
function your_model_function()
{
$result = execute_query($sql);
$rows = array();
if($result->num_rows)
{
while($row = $result->fetch_row())
$rows[] = $row;
}
return $rows;
}
2) use json_encode to encode your whole data array in json format
$data = $this->model->your_model_func();
echo json_encode($data);
3) Use the JSON in your success callback function
//writing success function of ajax
function(data)
{
for(var i in data)
{
var row = data[i];
// to acccesss the data of row ie json object you can use . operator
console.log(row.key)
// manipulate dom content.
}
}
NOTE: i have written a pseudo code only you cannot directly copy paste it to get result it's just to clear your mind.

jQuery calculating price if many elements on same page using same IDs?

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

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

Categories