How can i get total value after add paid value in php - javascript

I have make a managment system in which i m making sales page. I make all the fields. Now after entering the items, I want the management system to show me total of all and when i add paid money it show me left amount from total. Html Code is below
<table class="table table-bordered table-striped">
<thead>
<th>#</th>
<th>Item Name</th>
<th>Batch No</th>
<th>Remarks</th>
<th>Quantity</th>
<th>Cost Per Piece</th>
<th>Total</th>
<th>Action</th>
</thead>
<tbody id="tbody">
</tbody>
<center><button type="button" name="" onclick="additem()" class="btn btn-success"> Add</button></center></td>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><h3 style="color:red;">Total Amount</td>
<td><input type="number" id="totalamount" class="form-control" name="text" readonly /></td>
<tr>
<td></td>
<td> </td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><h3 style="color:red;">Paid</td>
<td><input type="number" name="paid" id="total10" oninput="calculateTotal()" class="form-control" /></td>
</tr>
<tr>
<td></td>
<td> </td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><h3 style="color:red;">G.T.Balance</td>
<td><input type="number" name="" id="gtotal" class="form-control" readonly /></td>
</tr>
</table>
Now the jquery code is
<script type="text/javascript">
let x = 0;
function additem() {
x++;
var html=`<tr;
<td><center>${x}</center></td>
<td><input type='text' class='form-control' name='product_name[]' required></td>
<td><input type='text' class='form-control' name='batch_no[]' required></td>
<td><input type='text' class='form-control' name='remarks[]' required></td>
<td><input id='qty${x}' type='number' class='form-control' oninput='calculate(${x})' name='total_qty[]' required></td>
<td><input id='cost${x}' type='number' class='form-control' oninput='calculate(${x})'name='cost[]' required></td>
<td><input type='number' class='form-control' id='total${x}' name='total[]' readonly required></td>
<td><button type='button' id='btn' class='btn btn-danger'><i class='fa fa-remove'></i></button></td>
</tr>`;
document.getElementById("tbody").insertRow().innerHTML= html;
}
function calculate(x) {
const qty = document.getElementById(`qty${x}`).value;
const cost = document.getElementById(`cost${x}`).value;
const totalElem = document.getElementById(`total${x}`);
totalElem.value = qty * cost
calculateTotal()
}
function calculateTotal() {
let fields = document.getElementsByName('total')
let total = 0
fields.forEach(f => {
total = total + parseInt(f.value)
})
document.getElementById('totalamount').value = total
let paid = document.getElementById('total10').value || 0 // If you change the id of the "paid" field, change it here too.
let subtotal = total - parseInt(paid)
document.getElementById('gtotal').value = subtotal
}
$(document).on('click',"#btn", function(e)
{
var r = $(this).closest('tr').remove();
x=0;
});
</script>
I have make a function name calculate total before it return me right value now it is returning me 0. Please kindly help me

Changes in var html variable:
From: name='total[]'
To: name='total'
Note: You must not be mixing JS and HTML together. There are also issues with your HTML table.
var html=`<tr>
<td><center>${x}</center></td>
<td><input type='text' class='form-control' name='product_name[]' required></td>
<td><input type='text' class='form-control' name='batch_no[]' required></td>
<td><input type='text' class='form-control' name='remarks[]' required></td>
<td><input id='qty${x}' type='number' class='form-control' oninput='calculate(${x})' name='total_qty[]' required></td>
<td><input id='cost${x}' type='number' class='form-control' oninput='calculate(${x})'name='cost[]' required></td>
<td><input type='number' class='form-control' id='total${x}' name='total' readonly required></td>
<td><button type='button' id='btn' class='btn btn-danger'><i class='fa fa-remove'></i></button></td>
</tr>`;

Related

I have make a html form in which I click on add button and a new row come. I want I want to get total amount of all rows

I make a page in which when I click on the button it makes a row. In row I store quantity and cost and total. Now I want to make a function that calculates the sum of all rows total and when I input paid value it subtracts from total amount and shows in grand total textbox.
Here is html code:
<table class="table table-bordered table-striped">
<thead>
<th>#</th>
<th>Item Name</th>
<th>Batch No</th>
<th>Remarks</th>
<th>Quantity</th>
<th>Cost Per Piece</th>
<th>Total</th>
<th>Action</th>
</thead>
<tbody id="tbody">
</tbody>
<center><button type="button" name="" onclick="additem()" class="btn btn-success"> Add</button></center></td>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><h3 style="color:red;">Total Amount</td>
<td><input type="number" id="totalamount" class="form-control" name="text" readonly /></td>
</tr>
<tr>
<td></td>
<td> </td>
<td></td>
<td></td>
<td></td>
<td><h3 style="color:red;">Miscellaneous</td>
<td><input type="number" name="paid" id="paid" class="form-control" /></td>
</tr>
<tr>
<td></td>
<td> </td>
<td></td>
<td></td>
<td></td>
<td><h3 style="color:red;">Paid</td>
<td><input type="number" name="paid" id="total10" class="form-control" /></td>
</tr>
<tr>
<td></td>
<td> </td>
<td></td>
<td></td>
<td></td>
<td><h3 style="color:red;">G.T.Balance</td>
<td><input type="number" name="" id="gtotal" class="form-control" readonly /></td>
</tr>
</table>
And Javascript code is
let x = 0;
function additem() {
x++;
var html=`<tr;
<td><center>${x}</center></td>
<td><input type='text' class='form-control' name='product_name'></td>
<td><input type='text' class='form-control' name='batch_no'></td>
<td><input type='text' class='form-control' name='remarks'></td>
<td><input id='qty${x}' type='number' class='form-control' oninput='calculate(${x})' id='qty' name='total_qty'></td>
<td><input id='cost${x}' type='number' class='form-control' oninput='calculate(${x})' id='cost' name='cost'></td>
<td><input type='number' class='form-control' id='total${x}' name='total' readonly></td>
<td><button type='button' id='btn' class='btn btn-danger'><i class='fa fa-remove'></i></button></td>
</tr>`;
document.getElementById("tbody").insertRow().innerHTML= html;
}
function calculate(x) {
const qty = document.getElementById(`qty${x}`).value;
const cost = document.getElementById(`cost${x}`).value;
const totalElem = document.getElementById(`total${x}`);
totalElem.value = qty * cost
}
Now help me to make a function that sum totals of all rows and put in total amount then subtract with value of paid and show in G Total.
First of all, welcome to Stack Overflow. Now, about your question:
In order to make it work I made a few modifications on your HTML code and added a javascript function, which in my testing worked, but if they ever fail, please contact me and I'll try to fix them.
HTML:
<table class="table table-bordered table-striped">
<thead>
<th>#</th>
<th>Item Name</th>
<th>Batch No</th>
<th>Remarks</th>
<th>Quantity</th>
<th>Cost Per Piece</th>
<th>Total</th>
<th>Action</th>
</thead>
<tbody id="tbody">
</tbody>
<center><button type="button" name="" onclick="additem()" class="btn btn-success"> Add</button></center>
</td>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<h3 style="color:red;">Total Amount
</td>
<td><input type="number" id="totalamount" class="form-control" name="text" readonly /></td>
</tr>
<tr>
<td></td>
<td> </td>
<td></td>
<td></td>
<td></td>
<td>
<h3 style="color:red;">Miscellaneous
</td>
<td><input type="number" name="paid" id="paid" class="form-control" /></td>
</tr>
<tr>
<td></td>
<td> </td>
<td></td>
<td></td>
<td></td>
<td>
<h3 style="color:red;">Paid
</td>
<td><input type="number" name="paid" id="total10" oninput="calculateTotal()" class="form-control" /></td>
</tr>
<tr>
<td></td>
<td> </td>
<td></td>
<td></td>
<td></td>
<td>
<h3 style="color:red;">G.T.Balance
</td>
<td><input type="number" name="" id="gtotal" class="form-control" readonly /></td>
</tr>
</table>
Javascript:
function calculate(x) {
const qty = document.getElementById(`qty${x}`).value;
const cost = document.getElementById(`cost${x}`).value;
const totalElem = document.getElementById(`total${x}`);
totalElem.value = qty * cost
calculateTotal()
}
function calculateTotal() {
let fields = document.getElementsByName('total')
let total = 0
fields.forEach(f => {
total = total + parseInt(f.value)
})
document.getElementById('totalamount').value = total
let paid = document.getElementById('total10').value || 0 // If you change the id of the "paid" field, change it here too.
let subtotal = total - parseInt(paid)
document.getElementById('gtotal').value = subtotal
}
Also, I don't know if the total10 in the paid field is supposed to be there (you might want to limit the row number to 10), but I recommend you giving it a unique ID and changing it in the code, as I indicated with the comment.
I try to adjust your code as little as possible, so you can basically use it directly
I did a few things
First thing
In your additem function, add a custom class attribute to the Total field
Originally
<input type='number' class='form-control'....
Replace with
<input type='number' class='form-control row-total'...
This is for the convenience of counting all the amounts at once, I will explain later
Second thing
I added the totalAmount function, which will find all the fields with custom class names just now, and run back and forth to add up all the money
It should be noted that when I create the totalAmount function, I put it into the calculate function, so that whenever you calculate the amount of the current column, the total amount of all columns will be calculated at the same time
Third thing
Since there is still need to calculate how much to pay and calculate with the total amount, a refreshTotalAmount function is established here, which will take out the total amount, and the payment amount for simple calculations, and establish an imput listener, whenever a payment is made When the amount changes, it will call the refreshTotalAmount function to refresh the total amount
let x = 0;
function additem() {
x++;
var html = `<tr;
<td><center>${x}</center></td>
<td><input type='text' class='form-control' name='product_name'></td>
<td><input type='text' class='form-control' name='batch_no'></td>
<td><input type='text' class='form-control' name='remarks'></td>
<td><input id='qty${x}' type='number' class='form-control' oninput='calculate(${x})' id='qty' name='total_qty'></td>
<td><input id='cost${x}' type='number' class='form-control' oninput='calculate(${x})' id='cost' name='cost'></td>
<td><input type='number' class='form-control row-total' id='total${x}' name='total' readonly></td>
<td><button type='button' id='btn' class='btn btn-danger'><i class='fa fa-remove'></i></button></td>
</tr>`;
document.getElementById("tbody").insertRow().innerHTML = html;
}
function calculate(x) {
const qty = document.getElementById(`qty${x}`).value;
const cost = document.getElementById(`cost${x}`).value;
const totalElem = document.getElementById(`total${x}`);
totalElem.value = qty * cost;
totalAmount();
}
function totalAmount(){
let sum = 0;
const elements = document.getElementsByClassName('row-total');
Array.prototype.forEach.call(elements, function(el) {
sum += parseInt(el.value);
});
document.getElementById("totalamount").value = sum;
}
function refreshTotalAmount(){
const paidCash = document.getElementById("total10").value;
const totalCash = document.getElementById("totalamount").value
document.getElementById("totalamount").value = totalCash - paidCash;
}
document.getElementById("total10").oninput = function() {
refreshTotalAmount();
}
<table class="table table-bordered table-striped">
<thead>
<th>#</th>
<th>Item Name</th>
<th>Batch No</th>
<th>Remarks</th>
<th>Quantity</th>
<th>Cost Per Piece</th>
<th>Total</th>
<th>Action</th>
</thead>
<tbody id="tbody">
</tbody>
<center><button type="button" name="" onclick="additem()" class="btn btn-success"> Add</button></center>
</td>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<h3 style="color:red;">Total Amount
</td>
<td><input type="number" id="totalamount" class="form-control" name="text" readonly /></td>
</tr>
<tr>
<td></td>
<td> </td>
<td></td>
<td></td>
<td></td>
<td>
<h3 style="color:red;">Miscellaneous
</td>
<td><input type="number" name="paid" id="paid" class="form-control" /></td>
</tr>
<tr>
<td></td>
<td> </td>
<td></td>
<td></td>
<td></td>
<td>
<h3 style="color:red;">Paid
</td>
<td><input type="number" name="paid" id="total10" class="form-control" /></td>
</tr>
<tr>
<td></td>
<td> </td>
<td></td>
<td></td>
<td></td>
<td>
<h3 style="color:red;">G.T.Balance
</td>
<td><input type="number" name="" id="gtotal" class="form-control" readonly /></td>
</tr>
</table>
You can Run code snippet to see if the result is what you want, if I did not misunderstand you
In addition, it is recommended that when designing dynamic grammar, elements should be careful not to repeat ID
And strict check of the field value, if this is not for your own use,
I didn’t specifically mention it in the article because
It will blur the focus. You are asking a question, and I am solving it. If I negate the adjustment of your entire code, it will be meaningless, so I am only raising it now.
Also, welcome to stackoverflow
Have a good day :)

want to add a column dynamically by calculation the previous column jQuery

Hello I have a pop up view where i fetch the data and put it in a table like the image below.
the are values in QTY Field .The main task is that when i edit the QTY input text for example I make this 200 then after this there will be a new column added next to that column and will hold the remaining value .for example Initial 500 ,change to 200 then the next column will show(500-200)=300 ,and it will continue as i keep changing like below image .I trying to make something like the below one.
I am using blur event but the new column is creating at last not after the changing column and can't calculate the values.like i show in second image
my sample code is something like below
<table border="1" cellspacing="0">
<tr>
<th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
<th>S. No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Tamil</th>
<th>English</th>
<th>Computer</th>
<th>Total</th>
</tr>
<tr>
<td><input type='checkbox' class='case'/></td>
<td>1.</td>
<td><input type='text' id='first_name' name='first_name[]'/></td>
<td><input type='text' id='last_name' name='last_name[]'/></td>
<td><input type='text' id='tamil' name='tamil[]'/></td>
<td><input type='text' id='english' name='english[]'/> </td>
<td><input type='text' id='computer' name='computer[]'/></td>
<td><input type='text' id='total' name='total[]'/> </td>
</tr>
</table>
<button type="button" class='delete'>- Delete</button>
<button type="button" class='addmore'>+ Add More</button>
<p>
<input type='submit' name='submit' value='submit' class='but'/></p>
****Javascript code**
var i=2;
$("#last_name").blur(function(){
var data="<tr><td><input type='checkbox' class='case'/></td><td>"+i+".
</td>";
data +="<td><input type='text' id='first_name"+i+"'
name='first_name[]'/></td> <td><input type='text' id='last_name"+i+"'
name='last_name[]'/></td><td><input type='text' id='tamil"+i+"'
name='tamil[]'/></td><td><input type='text' id='english"+i+"'
name='english[]'/></td><td><input type='text' id='computer"+i+"'
name='computer[]'/></td><td><input type='text' id='total"+i+"'
name='total[]'/></td></tr>";
$('table').append(data);
i++;
})
I Hope I make my question clear by the images help needed .Thanks
To append after row replace $('table').append(data) whith
$(data).insertAfter as demo below
var i=2;
var addRow = function(){
var data="<tr><td><input type='checkbox' class='case'/></td><td>"+i+". </td>";
data +="<td><input type='text' name='first_name[]'/></td> <td><input type='text' name='last_name[]'/></td><td><input type='text' name='tamil[]'/></td><td><input type='text' name='english[]'/></td><td><input type='text' name='computer[]'/></td><td><input type='text' name='total[]'/></td></tr>";
$(data).insertAfter($(this).closest('tr'))
i++;
}
$(document).on('blur', 'input[name="last_name[]"]', addRow)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1" cellspacing="0">
<tr>
<th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
<th>S. No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Tamil</th>
<th>English</th>
<th>Computer</th>
<th>Total</th>
</tr>
<tr>
<td><input type='checkbox' class='case'/></td>
<td>1.</td>
<td><input type='text' name='first_name[]'/></td>
<td><input type='text' name='last_name[]'/></td>
<td><input type='text' name='tamil[]'/></td>
<td><input type='text' name='english[]'/> </td>
<td><input type='text' name='computer[]'/></td>
<td><input type='text' name='total[]'/> </td>
</tr>
</table>
<button type="button" class='delete'>- Delete</button>
<button type="button" class='addmore'>+ Add More</button>
<p>
<input type='submit' name='submit' value='submit' class='but'/></p>
())
To calculate the diff you have to use the onchange event on first row to keep the original value (before change). Than on blur, when adding row, compute the difference beetwhen original saved value and actual value

How to get value of next input in <td> which is added dynamically

I append data to tbody which I get through ajax request. In backend I print data like this
echo "<tr>
<td><input type='text' name='sl_p_codes[]' id='p_code' value='{$data['p_code']}' ></td>
<td><input type='text' name='sl_products[]' id='qty' value='{$data['p_name']}' ></td>
<td><input type='text' id='product_qty' name='sl_p_qty[]' id='qt' value='01' size='2'></td>
<td><input type='hidden' name='sl_unit_cost[]' id='product_unit_price'></td>
<td><input type='text' id='product_total_cost' readonly name='sl_price[]' id='qty' value='{$data['p_price']}' ></td>
<td class='center'><a href='#' onclick='delrow(this);' class='btn btn-danger'>X</a></td>
</tr>";
If I change id='product_qty'(input field) the value of id='product_total_cost' (input field) should be updated with the value of id='product_unit_price'
You mean something like this:
$("#product_qty").on("change", function() {
$(this).closest("tr").find("#product_total_cost").val(
(parseFloat($(this).closest("tr").find("#product_unit_price").val()) * parseInt($(this).val())).toFixed(2)
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type='text' name='sl_p_codes[]' id='p_code' value='ABC011'></td>
<td><input type='text' name='sl_products[]' id='qty' value='01'></td>
<td><input type='number' id='product_qty' name='sl_p_qty[]' id='qt' value='01' size='2'></td>
<td><input type='hidden' name='sl_unit_cost[]' id='product_unit_price' value="1.00"></td>
<td><input type='text' id='product_total_cost' readonly name='sl_price[]' id='qty' value='1.00'></td>
<td class='center'><a href='#' onclick='delrow(this);' class='btn btn-danger'>X</a></td>
</tr>
</table>

Java script add days to date does not produce a result

Please can someone help
I have written some JavaScript that should add the number of days written into my form to the start date of a reservation. It should then output the date of return. I don't see any syntax errors but the script doesn't run. Please can someone help me identify the source of the problem.
JavaScript
<script type="application/javascript">
function ReturnDate(){
var reservationStart = document.getElementById('ReservationStart').value;
var requestedDays = parseInt(document.getElementById('days').value);
var returnDate = document.getElementById('ReturnDate');
var arrParts = reservationStart.split("/");
var myDate = new Date(arrParts[2], parseInt(arrParts[1])-1, parseInt(arrParts[0]) + requestedDays, 0, 0, 0, 0);
var sResult = ("0"+myDate.getDate()).substr(-2)+"/";
sResult += ("0"+(myDate.getMonth()+1)).substr(-2)+"/";
sResult += myDate.getFullYear();
document.getElementById('ReturnDate').value = sResult;
}
</script>
HTML
<form name="frmHTML" method="post" action="">
<table id="tables" class="form" style="width:100%">
<tr>
<td>Game ID</td>
<td><input type="text"
required autocomplete="off"
value= "<?php echo (isset($ID))?$ID:'';?>"
name="gameID"
id="gameID"
placeholder= "Enter A Number between 1 and 8"
style="width:80%"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit"
value= "Search For Game"
name= "FindDetails"
id= "FindDetails"
style= "width:80%" /></td>
</tr>
<tr>
<td>Game Name</td>
<td><input type= "text"
value = "<?php echo (isset($GameName))?$GameName:'';?>"
name="GameName"
id= "GameName"
readonly
style "width:80%" /></td>
</tr>
<tr>
<td>Game Rental Cost(per day)</td>
<td><input type= "text"
value = "<?php echo (isset($GameCost))?$GameCost:'';?>"
name="gameCost"
id="gameCost"
readonly
style= "width:80%" /></td>
</tr>
<tr>
<td>Number of days</td>
<td><input type= "text"
name="days"
id="days"
placeholder="Enter the number of days you wish to borrow the game for"
onkeyup = "mycalculate()"
autocomplete="off"
style="width:80%" /></td>
</tr>
<tr>
<td>Total Cost</td>
<td><input type="text"
value=""
name="total"
id= "total"
readonly
style="width:80%"/></td>
</tr>
<tr>
<td>Your Name</td>
<td><input type="text"
value=""
name="StudentName"
id="StudentName"
autocomplete="off"
style="width:80%"/></td>
</tr>
<tr>
<td>Date Start(dd/mm/yyyy)</td>
<td><input type="text"
value=""
name="ReservationStart"
id="ReservationStart"
onkeyup = "ReturnDate()"
autocomplete="off"
style="width:80%"/></td>
</tr>
<tr>
<td>Date End(dd/mm/yyyy)</td>
<td><input type="text"
value=""
name="ReturnDate"
id="ReturnDate"
style="width:80%"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit"
value= "Book Game Now"
name= "Submit"
id= "Submit"
style= "width:80%" /></td>
</tr>
</table>
</form>
The problem was the function name was the same as one of the variables. This meant the computer got confused.
The solution:
JavaScript
<script>
function myReturnDate(){
var reservationStart = document.getElementById('ReservationStart').value;
var requestedDays = parseInt(document.getElementById('days').value);
var returnDate = document.getElementById('ReturnDate');
var arrParts = reservationStart.split("/");
var myDate = new Date(arrParts[2], parseInt(arrParts[1])-1, parseInt(arrParts[0]) + requestedDays, 0, 0, 0, 0);
var sResult = ("0"+myDate.getDate()).substr(-2)+"/";
sResult += ("0"+(myDate.getMonth()+1)).substr(-2)+"/";
sResult += myDate.getFullYear();
document.getElementById('ReturnDate').value = sResult;
}
</script>
HTML
<form name="frmHTML" method="post" action="">
<table id="tables" class="form" style="width:100%">
<tr>
<td>Game ID</td>
<td><input type="text"
required autocomplete="off"
value= "<?php echo (isset($ID))?$ID:'';?>"
name="gameID"
id="gameID"
placeholder= "Enter A Number between 1 and 8"
style="width:80%"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit"
value= "Search For Game"
name= "FindDetails"
id= "FindDetails"
style= "width:80%" /></td>
</tr>
<tr>
<td>Game Name</td>
<td><input type= "text"
value = "<?php echo (isset($GameName))?$GameName:'';?>"
name="GameName"
id= "GameName"
readonly
style "width:80%" /></td>
</tr>
<tr>
<td>Game Rental Cost(per day)</td>
<td><input type= "text"
value = "<?php echo (isset($GameCost))?$GameCost:'';?>"
name="gameCost"
id="gameCost"
readonly
style= "width:80%" /></td>
</tr>
<tr>
<td>Number of days</td>
<td><input type= "text"
name="days"
id="days"
placeholder="Enter the number of days you wish to borrow the game for"
onkeyup = "mycalculate()"
autocomplete="off"
style="width:80%" /></td>
</tr>
<tr>
<td>Total Cost</td>
<td><input type="text"
value=""
name="total"
id= "total"
readonly
style="width:80%"/></td>
</tr>
<tr>
<td>Your Name</td>
<td><input type="text"
value=""
name="StudentName"
id="StudentName"
autocomplete="off"
style="width:80%"/></td>
</tr>
<tr>
<td>Date Start(dd/mm/yyyy)</td>
<td><input type="text"
value=""
name="ReservationStart"
id="ReservationStart"
onkeyup = "myReturnDate()"
autocomplete="off"
style="width:80%"/></td>
</tr>
<tr>
<td>Date End(dd/mm/yyyy)</td>
<td><input type="text"
value=""
name="ReturnDate"
id="ReturnDate"
style="width:80%"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit"
value= "Book Game Now"
name= "Submit"
id= "Submit"
style= "width:80%" /></td>
</tr>
</table>
</form>

Using the same jQuery in multiple operations

I have a small question and I hope someone can help me with it :D
I’m trying to create a product table, in which a user just add the quantity of a product and the jquery makes the multiplication to its value and gives the result
I already made this, and it works well:
<script>
$(document).ready(function(){
$('#quantity_1').keyup(function(){
var price_1 = $("#price_1").val();
var quantity_1 = $("#quantity_1").val();
quantity_1 = quantity_1.replace(/[^0-9]+/g, '');
$("#quantity_1").val(quantity_1);
var total_1 = price_1 * quantity_1;
$( "#total_1" ).val( total_1.toFixed(2) );
});
});
</script>
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Product Name</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
</table>
Working demo here:
http://jsfiddle.net/EnterateNorte/9kswL0gf/
But I would like to be able to add more than one line, like so:
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Name 1</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
<tr>
<td>Name 5</td>
<td><input type="hidden" name="product[5][price]" id="price_5" value="10.00" />23.00</td>
<td><input type="text" name="product[5][quantity]" id="quantity_5" /></td>
<td><input type="text" name="product[5][total]" id="total_5" value="0" /></td>
</tr>
<tr>
<td>Name 3</td>
<td><input type="hidden" name="product[3][price]" id="price_3" value="130.00" />10.00</td>
<td><input type="text" name="product[3][quantity]" id="quantity_3" /></td>
<td><input type="text" name="product[3][total]" id="total_3" value="0" /></td>
</tr>
<tr>
<td>Name 4</td>
<td><input type="hidden" name="product[4][price]" id="price_4" value="12.00" />10.00</td>
<td><input type="text" name="product[4][quantity]" id="quantity_4" /></td>
<td><input type="text" name="product[4][total]" id="total_4" value="0" /></td>
</tr>
</table>
And if it isn’t to much trouble, I would be awesome if it would SUM all the totals and show a gran total at the end of the table :)
Use:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var price = $(this).parent().prev().find('input').val();
var quantity = $(this).val();
var total = price * quantity;
$(this).parent().next().find('input').val( total.toFixed(2) );
});});
Working Demo
Update: For showing Grand Total
var sum = 0;
//iterate through each textboxes and add the values
$('[name*=total]').each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseInt(this.value);
}
});
Working Demo
What you can do is to find the elements using their relative position instead of hard coded ids
$(document).ready(function () {
$('input[id^="quantity_"]').keyup(function () {
var $tr = $(this).closest('tr');
var price = $tr.find('input[id^="price_"]').val();
var quantity = this.value;
var total = (price * quantity) || 0;
$tr.find('input[id^="total_"]').val(total.toFixed(2));
});
});
Demo: Fiddle
I've updated your code in Fiddle. You need to change in your markup a bit.
<tr>
<td>Product Name</td>
<td><input type="hidden" class="price" ... />10</td>
<td><input type="text" class="quantity" ... /></td>
<td><input type="text" class="total" ... /></td>
</tr>
$(document).ready(function(){
$('.quantity').keyup(function(){
var parent = $(this).closest("tr");
var price = $(".price", parent).val();
var quantity = $(".quantity", parent).val();
var total = price * quantity;
$(".total", parent).val(total.toFixed(2));
});
});
I would recommend you to use common class
HTML:
<tr>
<td>Name 5</td>
<td>
<input type="hidden" class="price" value="10.00" />10.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
<tr>
<td>Name 3</td>
<td>
<input type="hidden" class="price" value="130.00" />130.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
Script:
$('.quantity').keyup(function () {
var tr = $(this).closest('tr');
var price = tr.find('.price').val();
var quantity = $(this).val();
var total = price * quantity;
tr.find('.total').val(total.toFixed(2));
});
DEMO
Modify your table:
<table border="1" cellpadding="5px" cellspacing="0" id='table' >
<!-- your rows with inputs -->
<tr>
<td>
<input id='totalSum' value='0' type='text' />
</td>
</tr>
</table>
Make all your 'total' inputs readonly by adding 'readonly' attribute.
js code:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var total = 0;
$('#table tr').each(function(i,item){
var price = parseFloat($(item).find('[name*=price]').val().replace(',','.'));
var quantity = parseInt($(item).find('[name*=quantity]').val());
if(!isNaN(price) && !isNan(quantity)){
total += price*quantity;
}
});
$("#totalSum").val(total.toFixed(2));
});
});

Categories

Resources