Edit Quantity Using Javascript price will adjust - javascript

I'm currently doing an project on online shopping cart, whereby customers can edit the quantity before checkout. I wanted to make it such that when customer edit the quantity, the price of the item and total price of all items will be adjusted. I know I can achieve that though javascript. Can't really work and understand it. It will be nice if someone would help me. Thank you so so much!
Ps: I am not sure if my codes are correct, but here's what I tried:
<script type="text/javascript">
function update(form){
var quantity = document.getElementById('#quantity');
var price = quantity * ($list['price']);
document.getElementById("price").value = price;
​}
</script>`
I have not done for the total price yet because the price itself isn't working. I know there's something I miss out. Hope someone can enlighten me.
My HTML:
`//database query
<td align='middle'><input type="number" onChange="update(this)" id="quantity" name="quantity" min="1" max='<?php echo $list['quantity'] ?>' value='1'></td>
<td><input type="text" id="price" value='<?php echo $list['price'] ?>' readonly></td>
<td><input type="text" name="amount" id="amount" readonly></td>`
I may have made stupid mistakes,so it will be nice if someone would explain about how javascript works if I got the wrong concepts. Thanks so much for helping!!:)

see demo here
look this line
quantity = document.getElementById('#quantity');
in this line remove '#'
quantity = document.getElementById(**'quantity'**);
and use parseint to convert to integer
var price = quantity * ($list['price']);
$list['price'] is false
to get price you need to do like this:
document.getElementById('price').value;
final code is :
form.php
//database query
<td align='middle'><input type="number" onChange="update(this)" id="quantity" name="quantity" min="1" max='<?php echo $list['quantity'] ?>' value='1'></td>
<td><input type="text" id="price" value='<?php echo $list['price'] ?>' readonly></td>
<td><input type="text" name="amount" id="amount" readonly></td>`
script.js
<script type="text/javascript">
function update(form){
var quantity = document.getElementById('quantity').value;
var price = document.getElementById("price").value;
price = parseInt(price);
quantity = parseInt(quantity);
var amount= quantity * price ;
document.getElementById("amount").value = amount;
}
</script>`

demo here
index.php
<form>
<table>
<thead>
<tr>
<th>quantity</th>
<th>price</th>
<th>amount</th>
</tr>
</thead>
<tbody>
<!-- if u use php
<?php foreach($i=0; $i<$count; $i++){ ?>
<tr>
<td><input type="number" id="quantity_$i" name="quantity_$i" min="1" max='20' value='1'
onChange="iteration = 1; update(iteration)" >
</td>
<td><input type="text" id="price_$i" value='25' readonly='readonly' ></td>
<td><input type="text" name="amount_$i" id="amount_$i" readonly value='25'></td>
</tr>
<?php } ?>
-->
<tr>
<td><input type="number" id="quantity_1" name="quantity_1" min="1" max='20' value='1'
onChange="iteration = 1; update(iteration)" >
</td>
<td><input type="text" id="price_1" value='25' readonly='readonly' ></td>
<td><input type="text" name="amount_1" id="amount_1" readonly value='25'></td>
</tr>
<tr>
<td><input type="number" id="quantity_2" name="quantity_2" min="1" max='20' value='1'
onChange="iteration = 2; update(iteration)" >
</td>
<td><input type="text" id="price_2" value='15' readonly='readonly' ></td>
<td><input type="text" name="amount_2" id="amount_2" readonly value='15'></td>
</tr>
</tbody>
</table>
</form>
script.js
function update(iteration){
// alert(iteration);
var quantity = document.getElementById('quantity_' + iteration).value;
// alert('quantity_' + iteration);
var price = document.getElementById('price_' + iteration).value;
price = parseInt(price);
quantity = parseInt(quantity);
var amount= quantity * price ;
document.getElementById('amount_' + iteration).value = amount;
}

Related

Javascript Quantity Validation Multiple Inputs

I'm new to programming and still learn. I just want to ask how to make code validation for more than one input? I have data table item. I want to run validation input for each row.
My Code below is only run for the first row, and cannot running in the second row.
<tr>
<td><input id="stock" type="number" name="stock" value="<?php echo $row->stock; ?>" readonly></td>
<td><input id="qty" onInput="calc();" type="number" name="qty"></td>
</tr>
<script type="text/javascript">
function calc(){
var stock = document.getElementById("stock").value;
var qty = document.getElementById("qty").value;
if(qty > stock){
alert("Qty More Than Stock!");
document.getElementById("qty").value = 1;
}
}
</script>
You can use querySelectorAll with an data-attribute for select all inputs then forEach it and check the value like:
document.querySelectorAll('input[data-check]').forEach(el => {
el.addEventListener('change', () => {
if (parseInt(el.value) > parseInt(el.parentElement.previousElementSibling.children[0].value)) {
alert("Qty More Than Stock!");
el.value = 0;
}
});
});
<table>
<tr>
<td>Stock</td>
<td>Qty</td>
</tr>
<tr>
<td><input id="stock" type="number" name="stock" value="2" readonly></td>
<td><input data-check type="number" name="qty"></td>
</tr>
<tr>
<td><input id="stock" type="number" name="stock" value="3" readonly></td>
<td><input data-check type="number" name="qty"></td>
</tr>
</table>
PS. Remember to use always a structure like my example else my code probably doesn't work.in fact el.parentElement.previousElementSibling.children[0].value it's like say: element - parent of element (td) - previous element (other td) - the first children of the previus element (input).
Another option is use another data-attribute for select the stock value like:
document.querySelectorAll('input[data-check]').forEach(el => {
el.addEventListener('change', () => {
let stock = document.querySelector('input[data-index="'+el.dataset.stock+'"]');
if (parseInt(el.value) > parseInt(stock.value)) {
alert("Qty More Than Stock!");
el.value = 0;
}
});
});
<table>
<tr>
<td>Stock</td>
<td>Qty</td>
</tr>
<tr>
<td><input data-index='0' type="number" name="stock" value="2" readonly></td>
<td><input data-check data-stock='0' type="number" name="qty"></td>
</tr>
<tr>
<td><input data-index='1' type="number" name="stock" value="25" readonly></td>
<td><input data-check data-stock='1' type="number" name="qty"></td>
</tr>
</table>

Price Calculation in Javascript/Codeigniter

I want to calculate the Total Price for the order. I got a formula::
TotalWithoutTax = (UnitPrice*Quantity)+Transportation+Premium-Discount
TotalAmtInclTax = TotalWithoutTax + TotalTax
But I cannot get the output. Please help me and give me some advise on this. Thank You.
Javascript:
function calcPrice(qty[], unit_price[], gp[], discount[], totalwithouttax, totaltax, totalamtincltax) {
var quantity = document.getElementById('qty[]').value;
var unitPrice = document.getElementById('unit_price[]').value;
var premium = document.getElementById('gp[]').value;
var discount = document.getElementById('discount[]').value;
var transportation = document.getElementById('transportation[]').value;
var totalwithouttax = (unitPrice * quantity) + premium + transportation - discount;
document.getElementById(totalwithouttax).value = Math.round(totalwithouttax);
return true;
var totalwithouttax = document.getElementById('totalwithouttax').value;
var totaltax = document.getElementById('totaltax').value;
var totalamtincltax = totalwithouttax + totaltax;
document.getElementById(totalamtincltax).value = Math.round(totalamtincltax);
return true;
}
View:
<!-- **************************** START OF ITEM LIST 1 ************************ -->
<tr class="item-details">
<td><span class="rowNumber">1</span></td>
<td class="">
<?php
$options = array(
'' => '~Choose An Item~'
);
foreach ($item as $rows){
$options[$rows->id] = $rows->item_name;
}
$select = array(
'id' => 'item_name',
'class' => 'form-control'
);
echo form_dropdown('item_name[]', $options,set_value('item_name'),$select);
?>
</td>
<td class=""><input type="number" class="item-qty" name="qty[]" /></td>
<td><input type="number" name="weight[]" class="weight" /></td>
<td><input type="number" name="transportation[]" class="transporation" onkeyup="calcPrice(qty[],unit_price[],gp[],discount[],totalwithouttax,totaltax,totalamtincltax);" /></td>
<td><input type="text" id="gp[]" name="gp[]" value="" onkeyup="calcPrice(qty[],unit_price[],gp[],discount[],totalwithouttax,totaltax,totalamtincltax);" /></td>
<td><input type="text" id="discount[]" name="discount[]" value="" onkeyup="calcPrice(qty[],unit_price[],gp[],discount[],totalwithouttax,totaltax,totalamtincltax);" /></td>
<td><input type="text" id="unit_price[]" name="unit_price[]" value="" onkeyup="calcPrice(qty[],unit_price[],gp[],discount[],totalwithouttax,totaltax,totalamtincltax);" /></td>
<td align="right">
<input type="text" id="totalwithouttax" name="totalwithouttax" value="" onkeyup="calcPrice(qty[],unit_price[],gp[],discount[],totalwithouttax,totaltax,totalamtincltax);" readonly>
</td>
<td align="right">
<input type="text" id="totaltax" name="totaltax" value="" onkeyup="calcPrice(qty[],unit_price[],gp[],discount[],totalwithouttax,totaltax,totalamtincltax);" readonly>
</td>
<td align="right">
<input type="text" id="totalamtincltax" name="totalamtincltax" value="" onkeyup="calcPrice(qty[],unit_price[],gp[],discount[],totalwithouttax,totaltax,totalamtincltax);" readonly>
</td>
</tr><br/>
document.getElementById("totalwithouttax").value=Math.round(totalwithouttax);
this can solve a lot of issues a think

How to sum values inside loop using onchange javascript

how do i sum values inside loop using javascript onchange / onkeyup ? i put each of them, numbered id based on the loop...
here is my code example
<?php
$no = 1;
foreach($data as $array)
{
echo "<tr>";
echo "<td><input type='number' id='price".$no."' value='.$array['price'].'></td>";
echo "<td><input type='number' id='discount".$no."' onkeyup='keyup(".$no.")'></td>";
echo "<td><input type='number' id='total_price".$no."'></td>";
echo "</tr>";
$no++;
}
<input type='text' readonly id='total_payment'>
and here is my javascript
function keyup(id)
{
var price = $('#price'+id).val();
var discount= $('#discount'+id).val();
total_price = parseFloat(price) - parseFloat(discount);
$('#total_price'+id).val(total_price);
}
when i change the value of discount,it sum all of total_price field into total_payment.
how to do that ? i already set some form to show the example
JSFIDDLE: https://jsfiddle.net/20gb8n1g/
Attaching on keyup handlers on every input and then doing the math should work in a "in real time" fashion
$( document ).ready(function() {
$("body").on("keyup", "input", function(event){
$(this).closest(".line").find(".tot_price").val( $(this).closest(".line").find(".qty").val()*$(this).closest(".line").find(".value").val() );
$(this).closest(".line").find(".total_price").val( $(this).closest(".line").find(".tot_price").val()*1-$(this).closest(".line").find(".discount").val() );
var sum = 0;
$('.total_price').each(function() {
sum += Number($(this).val());
});
$(".grand_total").val(sum);
});
});
table {
border-collapse: collapse;
}
table, tr, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>Quantity</td>
<td>Price</td>
<td>Total Price</td>
<td>Discount</td>
<td>Total Price (Discount)</td>
</tr>
<tr class="line">
<td><input type='number' class="qty" value='2'></td>
<td><input type='number' class="value" value='20000'></td>
<td><input type='number' class="tot_price" value='40000'></td>
<td><input type='number' class="discount" min='0.1' step='0.1'></td>
<td><input type='number' value='40000' class='total_price'></td>
</tr>
<tr class="line">
<td><input type='number' class="qty" value='2'></td>
<td><input type='number' class="value" value='20000'></td>
<td><input type='number' class="tot_price" value='40000'></td>
<td><input type='number' class="discount" min='0.1' step='0.1'></td>
<td><input type='number' value='40000' class='total_price'></td>
</tr>
<tr class="line">
<td><input type='number' class="qty" value='2'></td>
<td><input type='number' class="value" value='20000'></td>
<td><input type='number' class="tot_price" value='40000'></td>
<td><input type='number' class="discount" min='0.1' step='0.1'></td>
<td><input type='number' value='40000' class='total_price'></td>
</tr>
<tr class="line">
<td><input type='number' class="qty" value='2'></td>
<td><input type='number' class="value" value='20000'></td>
<td><input type='number' class="tot_price" value='40000'></td>
<td><input type='number' class="discount" min='0.1' step='0.1'></td>
<td><input type='number' value='40000' class='total_price'></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan='4' style='text-align:right;'>Total Payment</td>
<td><input type='number' class="grand_total"></td>
</tr>
</tfoot>
</table>
Key parts:
Every row has the class "line" to stop looking up when you're doing the math
Every input has a class depending on what it is, instead of an id.
The handler basically does:
check where you triggered "keyup"
Look up to the "line" and then down to the "tot_price"
Change that value to the "value" * "qty" of that "line"
Look up to the "line" and then down to the "total_price"
Change that value to the "tot_price" * 1- "discount" of that "line"
Finally update "grand_total" with the sum of all those "total_price"s
I got it to work on my local machine by taking what you had on your JsFiddle and modifying one of the parseFloat() calls, which you incorrectley called using a capital L like this: parseFLoat(). This should do the trick for you.
Note: Be certain that your path you to your index.js(or whatever file your JavaScript is in) is correct within your <head> tag.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="index.js"></script>
</head>
<body>
<table>
<tbody>
<tr>
<td>Quantity</td>
<td>Price</td>
<td>Total Price</td>
<td>Discount</td>
<td>Total Price (Discount)</td>
</tr>
<tr>
<td><input type='number' readonly value='2'></td>
<td><input type='number' readonly value='20000'></td>
<td><input type='number' id='tot_price1' readonly value='40000'></td>
<td><input type='number' min='0.1' step='0.1' id='discount1' onkeyup='newFunc()'></td>
<td><input type='number' readonly value='40000' id='total_price1'></td>
</tr>
<tr>
<td><input type='number' readonly value='3'></td>
<td><input type='number' readonly value='30000'></td>
<td><input type='number' id='tot_price2' readonly value='90000'></td>
<td><input type='number' min='0.1' step='0.1' id='discount2'></td>
<td><input type='number' readonly value='90000'></td>
</tr>
<tr>
<td><input type='number' readonly value='2'></td>
<td><input type='number' readonly value='10000'></td>
<td><input type='number' id='tot_price3' readonly value='20000'></td>
<td><input type='number' min='0.1' step='0.1' id='discount3'></td>
<td><input type='number' readonly value='20000'></td>
</tr>
<tr>
<td><input type='number' readonly value='4'></td>
<td><input type='number' readonly value='10000'></td>
<td><input type='number' id='tot_price4' readonly value='40000'></td>
<td><input type='number' min='0.1' step='0.1' id='discount4'></td>
<td><input type='number' readonly value='40000'></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan='4' style='text-align:right;'>Total Payment</td>
<td><input type='number' ></td>
</tr>
</tfoot>
</table>
</body>
</html>
JS:
function newFunc() {
var total_price = $('#tot_price1').val();
var discount = $('#discount1').val();
n_discount = parseFloat(discount) / 100;
v_discount = parseFloat(total_price) * parseFloat(n_discount);
t_discount = parseFloat(total_price) - parseFloat(v_discount);
$('#total_price1').val(t_discount);
}
i cant output the total amount of price. here is my code.
HTML.
<?php foreach($result as $row): ?>
<!-- <td><input type="hidden" name="material_id[]" value="<?= $order_no = generate_random(5); ?>">
</th> -->
<td><input type="hidden" name="material_id[]" value="<?= encode($row->material_id); ?>">
<?= $row->material_id; ?></td>
<td><input type="hidden" name="" value="<?= $row->material_name; ?>">
<?= $row->material_name; ?></td>
<td><input type="hidden" id="price'<?= $no;?>'" name="material_price[]" value="<?= $row->material_price; ?>">
<?= $row->material_price; ?></td>
<td <?php if($row->material_status == 'Inactive'){
echo 'class="text-danger"';
}else{
echo 'class="text-success"';
} ?> >
<?= $row->material_status; ?>
</td>
<div class="form-group">
<td>
<input type="number" onkeyup="autosum(<?= $no;?>)" id="qty'<?= $no;?>" value="" name="material_qty[]" class="form-control" style="width:80px;height: 30px;"/>
</td>
</div>
<div class="form-group">
<td>
<input type="text" readonly id="total'<?= $no;?>'" value="" class="form-control" style="width:80px;height: 30px;"/>
</td>
</div>
</tr>
<?php $no++; ?>
<?php endforeach;?>
<tr style='position:absolute;margin-left: 895px;margin-top:20px;'>
<td colspan='4' >Grand Total :</td>
<td><input type='number' id="grandtotal" class="form-control" readonly style="width: 80px;"></td>
</tr>
<input type="hidden" name="order_no" value="<?= $order_no = generate_random(5); ?>" style="width:50px;height: 30px;">
<input type="hidden" name="order_id" value="<?= $order_id =generate_random(5); ?>" style="width:50px;height: 30px;">
</tbody>
</table>
<br>
<br>
<br>
<button type="button" class="fadeIn second btn btn-secondary" style="margin-left:890px;margin-top:50px;">CANCEL</button>
<button type="submit" class="fadeIn second btn btn-danger" style="margin-left:1000px;margin-top:-50px;background-color: red;">ORDER</button>
</form>

how can I get a value from the nth element of the closest 'tr'?

I have a dynamic table that contains price, quantity and subtotal on each row. I am trying to write a javascript method that automatically multiples the price and quantity values on each keyup and outputs them as the subtotal.
$('input.value').keyup( function() {
var row = $(this).closest('tr');
var val1 = row.find(':nth-child(1)').value;
var val2 = row.find(':nth-child(2)').value;
console.log(val1);
console.log(val2);
output = row.find(':nth-child(3)');
output.value = val1 * val2;
});
This is as far as I've gotten so far, the console log just shows "undefined" as the values for val1, and val2. Why is this? Am I misunderstanding how .find() works?
I have tried searching on both stack exchange and google, and I can't seem to find a good example of using nth-child based on the currently selected row.
Here is a simplified version of the table row. Each table row has an id based on it's row number.
<tr id = "row_#">
<td>
<?php echo $this->Form->text("Items.{$key}.quantity", array('value' => $item['quantity'], 'class' => 'value')); ?>
</td>
<td>
<?php echo $this->Form->text("Items.{$key}.price", array('value' => $item['price'], 'class' => 'value')); ?>
</td>
<td>
<?php echo $this->Form->text("Items.{$key}.total", array('value' => number_format( $item['price']*$item['quantity'], 2), 'class' => 'subtotal')); ?>
</td>
</tr>
I am using jquery, and cakephp 2.7
In your code, row.find(':nth-child(1)') selects a <td> element -- the first child of the <tr>. But it seems that you want to select <input> elements in each row to get their values.
In my example, below, I've given each input a class that identifies it as a "quantity", "price", or "total" field. I find the closest row to the current <input>. Then I find the value for each input within that row, calculate the total, and set the value of the "total" <input> to that number.
I'm using jQuery's selector context, which is internally equivalent to find().
$('input.value').keyup(function() {
var $row = $(this).closest('tr');
$output = jQuery('input.total', $row),
quantity = jQuery('input.quantity', $row).val(),
price = jQuery('input.price', $row).val(),
total = quantity * price;
$output.val(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" class="value quantity" /></td>
<td><input type="text" class="value price" /></td>
<td><input type="text" class="total" /></td>
</tr>
<tr>
<td><input type="text" class="value quantity" /></td>
<td><input type="text" class="value price" /></td>
<td><input type="text" class="total" /></td>
</tr>
<tr>
<td><input type="text" class="value quantity" /></td>
<td><input type="text" class="value price" /></td>
<td><input type="text" class="total" /></td>
</tr>
</table>
You can use nth-child selectors rather than classes, if you prefer. But remember that "nth" children are the <td> elements, not the <input> elements. You'll need to select the <input> within each "nth" <td> child. Something like:
$row.find('td:nth-child(1) input').val()
See the example below:
$('input.value').keyup(function() {
var $row = $(this).closest('tr');
$output = $row.find('td:nth-child(3) input'),
quantity = $row.find('td:nth-child(1) input').val(),
price = $row.find('td:nth-child(2) input').val(),
total = quantity * price;
$output.val(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" class="value" /></td>
<td><input type="text" class="value" /></td>
<td><input type="text" /></td>
</tr>
<tr>
<td><input type="text" class="value" /></td>
<td><input type="text" class="value" /></td>
<td><input type="text" /></td>
</tr>
<tr>
<td><input type="text" class="value" /></td>
<td><input type="text" class="value" /></td>
<td><input type="text" /></td>
</tr>
</table>
jQuery has no value property....use val() and assuming selectors are valid it should work
var val1 = row.find(':nth-child(1)').val();

subtract two values using jquery / javascript

<?php $j=1; ?>
<table class="table">
<thead>
<tr>
<th>Sl No</th>
<th>Item</th>
<th>Current Quantity</th>
<th>Procuring Quantity</th>
<th>Updated Quantity</th>
</tr>
</thead>
<?php
$res=$_POST['supply'];
$result=explode("&",$res);
for($i=0;$i<count($result);$i++){ ?>
<tbody>
<tr class="info">
<?php
$name=$result[$i];
$query=mysql_query("select * from item where item_name='$name'");
$row=mysql_fetch_array($query);
?>
<td><?php echo $j;?></td>
<td><input type="text" name="name[]" id="contact_name" required="required" class="form-control" value="<?php echo $result[$i]; ?>" readonly></td>
<td><input type="text" name="current[]" required="required" class="form-control" value="<?php echo $row['item_qua'];?>"></td>
<td><input type="text" name="procuring[]" id="procuring" required="required" class="form-control"></td>
<td><input type="text" name="updated[]" id="updated" required="required" class="form-control"></td>
</tr>
<?php $j++; } ?>
</tbody>
</table>
I want to subtract Procuring Quantity by Current Quantity.I want result in Updated Quantity. (Current Quantity - Procuring Quantity= Updated Quantity).
Try this : Read current qunatity from previous input and get procuring qunatity from current input. do substraction and add to updated quantity.
NOTE - You have put id for current, procuring and updated quantity and after finishing loop your html will have duplicate id. Please remove that part or assign logic to make unique id.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function(){
// bind change event to procuring quantity
$('input[name="procuring[]"]').change(function(){
var $parentTR = $(this).closest('.info');
// read value for current quantity.
var current = $parentTR.find('input[name="current[]"]').val();
// read value for procuring quantity.
var procuring = $(this).val();
// do substraction and set value in 5th column for updated quantity.
var updated = parseFloat(current) - parseFloat(procuring);
$parentTR.find('input[name="updated[]"]').val(updated );
});
});
</script>
Demo
You can do this by getting the value of the input box by .val() and also give id to current[] , i am giving the id as current. Use the code below to do this
<td><input type="text" name="name[]" id="contact_name" required="required" class="form-control" value="<?php echo $result[$i]; ?>" readonly></td>
<td><input type="text" name="current[]" id="current" required="required" class="form-control" value="<?php echo $row['item_qua'];?>"></td>
<td><input type="text" name="procuring[]" id="procuring" required="required" class="form-control"></td>
<td><input type="text" name="updated[]" id="updated" required="required" class="form-control"></td>
<script>
$(document).ready(function(){
$("input").keyup(function(){
var current = $("#current").val();
var procuring = $("#procuring").val();
$("#updated").val(current - procuring);
});
});
</script>
I hope this helps you

Categories