Jquery to total up lines on dynamically generated tables - javascript

I have some code that appends new table rows when data is inserted into an existing row.
You can see the code in action here.
On entering a product, the new row is appended to the table with a unique input name.
The user is then required to enter a price and qty.
What I want is a 2 step calculation. In the input box Total, I want the sum of price * qty for that specific row. Secondly, I want the div grandtotal to display the sum of all the input boxes, all dynamic to the number of rows the user inserts.
Normally I would just use:
function fill() {
var txt8 = document.getElementById("TextBox8").value;
var txt9 = document.getElementById("TextBox9").value;
document.getElementById("TextBox10").value = txt8 + txt9;
}
But this is for static a static table where names and ID's are known. How do I make this work for a dynamically generated table?
Apologies, I forgot to give you the fiddle link: http://jsfiddle.net/yUfhL/230/

To get all inputs that have an ID that starts with linetotal, you could write the following in jQuery:
$('input[id^=linetotal]')
Now, to calculate the total, just iterate over the collection:
var total = 0;
$('input[id^=linetotal]').each(function() {
total += parseInt(this.value, 10) || 0;
});
Your output, then:
$('#grandtotal').text(total);
Edit
To first calculate the line totals for every line, you could iterate through them like so:
$('table.order-list tr').each(function() {
var price = parseInt( $('input[name=price]', this).val(), 10 );
var qty = parseInt( $('input[name=qty]' , this).val(), 10 );
$('input[id^=linetotal]', this).val(price * qty);
});
Of course, you wouldn't have to iterate over all rows at all times. At the change event, you're only interested in the current row, which is accessible by $(this).closest('tr')

Related

Ajax Table Result Is Not Calculating Sum Of Each Row's Price Column

screenshot of sale page
Hi all. I have a sale page and another page which shows result according to the ajax post. I don't know if you can see the image but let me explain shortly.
The left side of the page shows the list of chosen products according to the product list on the right side which works with ajax post. I click on the right side product buttons and AJAX results bring the product to the left side list with the product name, quantity and price of the product. Everything works fine till this step.
The problem is when i am choosing a product and it comes to the list of sale, i need to calculate the sum of this table's price column and show in another div-span out of this table. And i need to this live when i added a new product. And now it is showing the sum result of only first row in product list. Not calculating all.
This is the script of sum:
<script>
var $form = $('#satis_bitir'),
$sumDisplay = $('#ara_toplam');
$form.on('keyup', 'input', function ()
{
var $summands = $form.find('#toplam_tutar');
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum.toFixed(2));
});
</script>
So how can i calculate the whole list's price columns and show in another div->span?
var updateCartAmount = function(){
var $form = $('#satis_bitir'),
$sumDisplay = $('#ara_toplam');
var $summands = $form.find('.toplam_tutar');
var sum = 0;
$summands.each(function ()
{
var value = Number($(this).val());
if (!isNaN(value)) sum += value;
});
$sumDisplay.val(sum.toFixed(2));
};
$.ajax({
type: 'GET',
url: 'your-url',
data: {},
success: function(){
updateCartAmount(); //call your updateCartAmount here when ajax done
}
});
Instead of using
#toplam_tutar
Try to use
.toplam_tutar
elements ids are unique means only the first div will be selected

Get X and Y position after searching an element in a HTML table

I'm having troubles thinking a solution to this problem.
I have this table and a JSON like this one:
{:id=>"e-123",
:subject_initials=>"IN",
:grade=>"12"}
I need to search on the table the id of the person (which in this case is "e-123") and search on the first row the initials of the subject and put the grade on the X and Y position.
The result of the example above should be something like this
Any idea how to do this?
Need to search through the heading inputs to get a column index and search through the user id inputs to get a row index then use eq() method to isolate the one you need to update
var $subjectInput = $('tr').first().find('input').filter(function() {
return this.value === data.subject_initials
});
var $idInput = $('tr').find('td:eq(1) input').filter(function() {
return this.value.toLowerCase() === data.id
});
var colIdx = $subjectInput.parent('td').index();
var rowIdx = $idInput.closest('tr').index();
$('tr').eq(rowIdx).find('td').eq(colIdx).find('input').val(data.grade)
Adding some additional classes on these 2 types of inputs would help make the selectors for finding them easier
If the rows are generated dynamically adding an ID to the row and course name class to the data entry inputs you could simplify the whole thing immensely
<tr id="e-123">
.....
<input class="form-control course_IN">
JS
$('#' + data.id).find('input.course_' + data.subject_initials).val(data.grade)
DEMO

how to add values from dynamically generated table row to one input box

function addTotal(){
var txtTotal = document.getElementById('txtTotal').value;
var txtGrandTotal = document.getElementById('txtGrandTotal');
txtGrandTotal.value += parseInt(txtTotal);
}
this is delete code
$(".delete-row").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
if the user deletes the row then the values from the Grand Total Should decrease. anything I should do any body
how to add values to the "Grand Total" to the Total input box Total is the dynamically created table data and I want to add values to that "Grand Total input box" but values are appending not the adding and also I have added an image of the screen or output. Thanks in advance.
Instead of
txtGrandTotal.value += parseInt(txtTotal);
as txtGrandTotal.value isn't converted to int, it is string
so you should do:
if (!txtGrandTotal.value)
txtGrandTotal.value = parseInt(txtTotal);
else
txtGrandTotal.value = parseInt(txtGrandTotal.value) + parseInt(txtTotal);
hey can I get your source code I need form IP billing master as you have? if you don't mind

Calculation using jquery onkeypress

I have this type of exercise in jquery. Go here http://jsfiddle.net/LAntL/3/
For Item 1, if I add #no of quantity of Size 7, it should be multiplied by Item 1's Price displayed in text box and the result should be shown in Item 1's Ext textbox.
then if I do same for size 8.5 of Item 1, it should perform the same.
But the Ext will have (Price x Size 7 Qty) + (Price x Size 8.5 Qty)
Same will happen for Item 2. And along with this, Total quantity and Total price will be updated on keypress event of each textbox.
I'm a beginner in jquery and got this killing exercise.
Please help someone.
Thanks in advance.
I'd suggest that you assign some classes to your fields so that jQuery can easily find them:
"lineQty" - add this class to all the qty fields
"lineTotal" - add this class to all the line total fields
"linePrice" - I think you can see where I'm going with this
"lineExt" - add to all ext fields
Then the following .keyup function will do the updates on all lines automatically.
$(document).ready(function() {
$(".lineQty").keyup(function() {
// 'this' is the field the user is typing in
// so find the tr that it belongs to
var $row = $(this).closest("tr"),
total = 0,
// get the price for the current row:
price = $row.find(".linePrice").val();
// loop through every qty field for the current row and add
// the entered value to the total, using unary plus to convert
// to a number, and a default of 0 if non-numeric data is entered
$row.find(".lineQty").each(function() {
total += +this.value || 0;
});
// set the total for the current row
$row.find(".lineTotal").val(total);
// set the price for the current row
$row.find(".lineExt").val(total * price);
// now add up the grand totals
var grandTotal = 0,
grandPrice = 0;
$(".lineTotal").each(function() {
grandTotal += +this.value || 0;
});
$(".lineExt").each(function() {
grandPrice += +this.value || 0;
});
$("[name='data[totalQuantity]']").val(grandTotal);
$("[name='data[totalPrice]']").val(grandPrice);
});
});
Working demo: http://jsfiddle.net/LAntL/5/ (only works on the first line because I couldn't be bothered assigning classes to all your fields - you would need to add the classes I talk about above to every field as per what I did for the first line).
Okay, you want to learn something, so I will describe a possible way, and don't give you the finished solution.
First of all, you should mark the tables which contains items with class="item". Now you can write a selector in jQuery which gets every item separately. Then you should mark all cells (<td>) which have a special function. Total, Price, Disc and Ext. Your table should look like this:
<table class="item">
<tr>
<td>...</td>
<td class="total">...</td>
<td class="price">...</td>
<td class="disc">...</td>
<td class="ext">...</td>
</tr>
</table>
Now you can write a selector for all input fields inside of the table with class "item".
$('.item input').change(function(){});
Inside of this function you can handle the calculation. At first I would recommend to get the item:
$('.item input').change(function(){
var item = $(this).closest('table.item');
var totalInput = $(item).find('.total input');
var priceInput = $(item).price('.price input');
// ...
var allWriteableInputs = $(item).find('input[readonly!="readonly"]');
// do the calculation
var sum = 0;
$(allWriteableInputs).each(function(i, input){
sum += $(input).val();
});
$(totalInput).val(sum);
});
If you go this way, you don't need:
The onkeypress="return isNumberKey(event);" and
the id="product1Total" for every inputbox
I hope this thought-provoking impulse helps you a little bit. You have still a long way to go, my young padawan ;-)

Javascript - filling textboxes with checkbox value

In my web application, I've set of checkboxes which on check populate a textbox above them.(If more than one checkbox is selected, then their values appear in the textbox separated by commas).
These set of checkboxes appear as rows in my HTML table.
Here's my HTML code.
<input type="text" id="newContactComment<%=rCount %>" name="newContactComment" size="45">
<input type="checkbox" id="commentText<%=rCount %>" name="commentText" value="<%=c.getComment_text() %>"
onclick="javascript:updateTextArea(<%=rCount%>);">
And the corresponding JS function is as follows:
function updateTextArea(rCount) {
var allVals = new Array();
$("#contactInfo input['commentText' + rCount]:checked").each(function() {
(allVals).push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
}
The rCount variable in the above function is the row # of my table.
Using this above, I'm not getting the expected behaviour..
For ex. If for row 1 of my table, I check chkbox 1 and 2, it correctly gets populated with values of those checkboxes. Now, for 2 of my table, I check only chkbox 3, it gets populated with the values 1,2 and 3 and not only 3 as I expect it to.
Any help will be greatly appreciated.
It would be better to use jQuery to set an event handler rather than setting it inline.
You want to use the onchange event not the onclick event.
If you add class names of checkboxes (or whatever you want) to the checkboxes the following will work:
$("input.checkboxes").change(function(){ //when checkbox is ticked or unticked
var par = $(this).closest("tr")[0];
var parID = par.id;
var patt1=/([0-9]+)$/g;
var rCount = parID.match(patt1); //Gets number off end of id
var allVals = new Array();
//Get all checkboxes in current row that are checked
$(par).find("td input.checkboxes:checked").each(function() {
allVals.push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
allVals = null; //empty array as not needed
});
I believe this or something along these lines will do what you want
You're trying to use the rCount variable from within the quoted string. Try this instead:
$("#contactInfo input['commentText" + rCount + "']:checked")

Categories

Resources