Calculating sum of td classes using js or jQuery - javascript

I have a dropdown select menu with various options (i.e. 5, 10, 15, 20...) that represents # of computers. The default select menu value is 5. I am using some js to multiply the dropdown selection by an amount (i.e. 10) and populates a table td with a class of .price-1. So, for example if the user leaves the default selection of 5, the calculated value of .price-1 is 50.
This is working fine. 
However, I then need to sum .price-1 with a few other <td> classes (i.e. .price-2, .price-3, .price-4...) to get a grand total in $ values that shows in #result.
How can I use js or jQuery to sum these td classes to get the grand total?
Below is my html of my table I need to sum.
<table id="tableOrderTotal" class="table tableTotal">
<tbody>
<tr>
<td>Item1</td>
<td class="price-1">calculated amount populated here</td>
</tr>
<tr>
<td>Item2</td>
<td class="price-2">calculated amount populated here</td>
</tr>
<tr>
<td>Item3</td>
<td class="price-3">13</td>
</tr>
<tr>
<td>Item3</td>
<td class="price-4">30</td>
</tr>
<tr class="summary">
<td class="totalOrder">Total:</td>
<td id="result" class="totalAmount"> </td>
</tr>
</tbody>
</table>

Get all td elements either using attribute value contains selector or by second td element of tr using :nth-child(). Now iterate over them using each() method and get sum using the text inside.
var sum = 0;
$('td[class*="price-"]').each(function() {
sum += Number($(this).text()) || 0;
});
$('#result').text(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableOrderTotal" class="table tableTotal">
<tbody>
<tr>
<td>Item1</td>
<td class="price-1">calculated amount populated here</td>
</tr>
<tr>
<td>Item2</td>
<td class="price-2">calculated amount populated here</td>
</tr>
<tr>
<td>Item3</td>
<td class="price-3">13</td>
</tr>
<tr>
<td>Item3</td>
<td class="price-4">30</td>
</tr>
<tr class="summary">
<td class="totalOrder">Total:</td>
<td id="result" class="totalAmount"></td>
</tr>
</tbody>
</table>
With Array#reduce method as #rayon suggested.
$('#result').text([].reduce.call($('td[class*="price-"]'), function(sum, ele) {
return sum + (Number($(ele).text()) || 0);
}, 0));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableOrderTotal" class="table tableTotal">
<tbody>
<tr>
<td>Item1</td>
<td class="price-1">calculated amount populated here</td>
</tr>
<tr>
<td>Item2</td>
<td class="price-2">calculated amount populated here</td>
</tr>
<tr>
<td>Item3</td>
<td class="price-3">13</td>
</tr>
<tr>
<td>Item3</td>
<td class="price-4">30</td>
</tr>
<tr class="summary">
<td class="totalOrder">Total:</td>
<td id="result" class="totalAmount"></td>
</tr>
</tbody>
</table>

jQuery Object has a direct attribute referring to the number of the matched elements.
var sum = $('td[class*="price-"]').length;
$('#result').text(sum);

Related

Push values to array as separate key value pairs

I have a project where I'm adding values from an attribute (comma separated integers) on a particular cell in each row of a table to an array in JS.
I know that if I create an array called myArray, then use myArray.push(121840,121841); the myArray.length result would be 2. This is what I expected. I had assumed (incorrectly) that since the value of the numbers attribute was the same format, e.g.: numbers="121840,121841", then the result would be the same using myArray.push($(this).attr('numbers'));, but I was mistaken as the length of that array is 1, instead of 2.
See below an example of what I'm trying to do and the issue I'm encountering.
Given a table like this where I'm grabbing the values from the last cell's numbers attribute:
<table border="1" width="100%">
<tbody emp-id="02" class="" name="Steve Smith">
<tr>
<td colspan="4">Steve Smith</td>
</tr>
<tr>
<td></td>
<td>2</td>
<td></td>
<td class="total" numbers="121856,121860">2</td>
</tr>
</tbody>
<tbody emp-id="01" name="Marky Mark">
<tr>
<td colspan="4">Marky Mark</td>
</tr>
<tr>
<td>1</td>
<td></td>
<td>1</td>
<td class="total" numbers="121840,121841">2</td>
</tr>
</tbody>
</table>
My JS would is:
$('table tbody tr').each(function() {
$(this).find('td:last').each(function(){
if ($(this).attr('numbers')) {
numbers.push($(this).attr('numbers'));
names.push($(this).parents("tbody").attr('name'));
}
});
});
In the above example, the array has the correct number values stored, (121856,121860,121840,12184), but the length is given as 2 as each cell's values was added as a single element, such that number[0]=121856,121860, instead of 121856.
How would I correct this so that each integer within the attribute is added as a single element?
JSFiddle: http://jsfiddle.net/jacbhg0n/3/
Any help would be greatly appreciated.
You can simply achieve that by splitting the numbers attribute string by using String.split() method while pushing it into the numbers array.
Live Demo :
const numbers = [];
const names = [];
$('table tbody tr').each(function() {
$(this).find('td:last').each(function(){
if ($(this).attr('numbers')) {
numbers.push($(this).attr('numbers').split(','));
names.push($(this).parents("tbody").attr('name'));
}
});
});
console.log(numbers.flat());
<table border="1" width="100%">
<tbody emp-id="02" class="" name="Steve Smith">
<tr>
<td colspan="4">Steve Smith</td>
</tr>
<tr>
<td></td>
<td>2</td>
<td></td>
<td class="total" numbers="121856,121860">2</td>
</tr>
</tbody>
<tbody emp-id="01" name="Marky Mark">
<tr>
<td colspan="4">Marky Mark</td>
</tr>
<tr>
<td>1</td>
<td></td>
<td>1</td>
<td class="total" numbers="121840,121841">2</td>
</tr>
</tbody>
</table>

Get text of specific element by index

I want to get the text of the second to last table row, so I tried to do this:
var tradeNumEl = $("td.trade-num").length - 2;
console.log($("td.trade-num")[tradeNumEl].text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="trade-num">100</td>
</tr>
<tr>
<td class="trade-num">101</td>
</tr>
<tr>
<td class="trade-num">102</td>
</tr>
<tr>
<td class="trade-num">103</td>
</tr>
<tr>
<td class="trade-num">104</td>
</tr>
<tr>
<td class="trade-num">105</td>
</tr>
</table>
However it gives me:
Uncaught TypeError: $(...)[tradeNumEl].text is not a function
How can I fix this? Here's the fiddle: https://jsfiddle.net/45a9sc6k/4/
Accessing a jQuery object by index returns the Element object at that index of the collection. It does not return a jQuery object - hence your error. To fix this, use eq() instead:
console.log($("td.trade-num").eq(tradeNumEl).text());
var tradeNumEl = $("td.trade-num").length - 2;
console.log($("td.trade-num").eq(tradeNumEl).text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="trade-num">100</td>
</tr>
<tr>
<td class="trade-num">101</td>
</tr>
<tr>
<td class="trade-num">102</td>
</tr>
<tr>
<td class="trade-num">103</td>
</tr>
<tr>
<td class="trade-num">104</td>
</tr>
<tr>
<td class="trade-num">105</td>
</tr>
</table>
You have to use eq() with index no as parameter. .eq(index) Reduce the set of matched elements to the one at the specified index.
var tradeNumEl = $("td.trade-num").length - 2;
console.log($("td.trade-num").eq(tradeNumEl).text() )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="trade-num">100</td>
</tr>
<tr>
<td class="trade-num">101</td>
</tr>
<tr>
<td class="trade-num">102</td>
</tr>
<tr>
<td class="trade-num">103</td>
</tr>
<tr>
<td class="trade-num">104</td>
</tr>
<tr>
<td class="trade-num">105</td>
</tr>
</table>
You also can create the object of the found element
///I want to get the text of the second to last table row using js and jquery. So I tried to do this:
var tradeNumEl = $("td.trade-num").length - 2;
console.log($($("td.trade-num")[tradeNumEl]).text(), tradeNumEl)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="trade-num">100</td>
</tr>
<tr>
<td class="trade-num">101</td>
</tr>
<tr>
<td class="trade-num">102</td>
</tr>
<tr>
<td class="trade-num">103</td>
</tr>
<tr>
<td class="trade-num">104</td>
</tr>
<tr>
<td class="trade-num">105</td>
</tr>
</table>

How to get a first td values of every table using JQuery?

I want to select all first td values using JQuery.
Here is my code:
<tr id="#ASPxGridView1_DXHeadersRow0">
<td id="ASPxGridView1_col0" class="dxgvHeader" onmousedown="ASPx.GHeaderMouseDown('ASPxGridView1', this, event);" style="border-top-width:0px;border-left-width:0px;">
<table style="width:100%;">
<tbody>
<tr>
<td>Status</td>
<td style="width:1px;text-align:right;"><span class="dx-vam"> </span></td>
</tr>
</tbody>
</table>
</td>
<td id="ASPxGridView1_col1" class="dxgvHeader" onmousedown="ASPx.GHeaderMouseDown('ASPxGridView1', this, event);" style="border-top-width:0px;border-left-width:0px;">
<table style="width:100%;">
<tbody>
<tr>
<td>Worksheet ID</td>
<td style="width:1px;text-align:right;"><span class="dx-vam"> </span></td>
</tr>
</tbody>
</table>
</td>
</tr>
I want to get only 2 td (Status.Worksheet ID) elements from my above code using JQuery
You can pass any valid CSS selector to JQuery, so all you need is:
$("td:first-child");
// This will find and group together all the `<td>` elements that are the first ones
// within their parent (<tr>).
var $results = $("td:first-child");
// You can loop over the set and work with the individual DOM elements...
$results.each(function(index, result){
// result is the DOM element we're looping over
console.log(result.textContent);
});
// Or, you can access a specific element by index:
console.log($results[0].textContent + ", " + $results[1].textContent);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr id="#ASPxGridView1_DXHeadersRow0">
<td id="ASPxGridView1_col0" class="dxgvHeader" onmousedown="ASPx.GHeaderMouseDown('ASPxGridView1', this, event);" style="border-top-width:0px;border-left-width:0px;"><table style="width:100%;">
<tbody>
<tr>
<td>Status</td>
<td style="width:1px;text-align:right;"><span class="dx-vam"> </span></td>
</tr>
</tbody>
</table>
</td>
<td id="ASPxGridView1_col1" class="dxgvHeader" onmousedown="ASPx.GHeaderMouseDown('ASPxGridView1', this, event);" style="border-top-width:0px;border-left-width:0px;">
<table style="width:100%;">
<tbody>
<tr>
<td>Worksheet ID</td>
<td style="width:1px;text-align:right;"><span class="dx-vam"> </span></td>
</tr>
</tbody>
</table>
</td>
</tr>

How to select the previous sibling of last cell which is not null from table, using JQuery

I have a table with following rows and cells:
<table id='table1'>
<tr id='row1'>
<th>index</th>
<th>Product</th>
<th>Description</th>
</tr>
<tr id='row2' name='row'>
<td name='index'>1</td>
<td name='product'>Apples</td>
<td name='description'>fruits</td>
</tr>
<tr id='row3' name='row'>
<td name='index'>2</td>
<td name='product'>Bananas</td>
<td name='description'>fruits</td>
</tr>
<tr id='row4' name='row'>
<td name='index'>3</td>
<td name='product'>Carrots</td>
<td name='description'>vegetables</td>
</tr>
<tr id='row5' name='row'>
<td name='index'>4</td>
<td name='product'></td>
<td name='description'></td>
</tr>
</table>
I would like to select the index of the tr which is in this case is the last td and does not have any data under Product Column. I have tried following JQuery function but they do not work:
Sibling method
var lastrow=$('td[name=product]:not(:empty):last ~ [name=index]').html();
and also
previous method
var lastrow=$('td[name=product]:not(:empty):last').prev().html();
But I cannot get the index number of last tr which has no data in its Product heading. In other words I am unable to get the td with name=index in the tr which does not have any data in td with name=product. Does anyone know what am I doing wrong or how can I achieve what I am looking for?
Find the not empty cell and select the previous cell from it:
var lastCellBeforeCellWithNoData = $('td[name=product]:not(:empty):last').prev('[name=index]');
console.log(lastCellBeforeCellWithNoData.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='table1'>
<tr id='row1'>
<th>index</th>
<th>Product</th>
<th>Description</th>
</tr>
<tr id='row2' name='row'>
<td name='index'>1</td>
<td name='product'>Apples</td>
<td name='description'>fruits</td>
</tr>
<tr id='row3' name='row'>
<td name='index'>2</td>
<td name='product'>Bananas</td>
<td name='description'>fruits</td>
</tr>
<tr id='row4' name='row'>
<td name='index'>3</td>
<td name='product'>Carrots</td>
<td name='description'>vegetables</td>
</tr>
<tr id='row5' name='row'>
<td name='index'>4</td>
<td name='product'></td>
<td name='description'></td>
</tr>
</table>
If you want to get the tr index use this
var trIndex = $('td[name=product]:empty').parent().index();
Else if you want to the select the name="index" use this one
var nameIndex = $('td[name=product]:empty').prev();
var trIndex = $('td[name=product]:empty').parent().index();
var nameIndex = $('td[name=product]:empty').prev().text();
console.log('Tr Index->'+trIndex, ', name="index"->'+nameIndex);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='table1'>
<tr id='row1'>
<th>index</th>
<th>Product</th>
<th>Description</th>
</tr>
<tr id='row2' name='row'>
<td name='index'>1</td>
<td name='product'>Apples</td>
<td name='description'>fruits</td>
</tr>
<tr id='row3' name='row'>
<td name='index'>2</td>
<td name='product'>Bananas</td>
<td name='description'>fruits</td>
</tr>
<tr id='row4' name='row'>
<td name='index'>3</td>
<td name='product'>Carrots</td>
<td name='description'>vegetables</td>
</tr>
<tr id='row5' name='row'>
<td name='index'>4</td>
<td name='product'></td>
<td name='description'></td>
</tr>
</table>
After spending some time understanding your question, I think that you are trying to accomplish the following: Returning the last cell's index where the "Product" column is not empty (note please try not to describe it as NULL as it is a very specific term for db storage). And also, I would think that it would be better that if you can do it using other language such as PHP to compare whether the retrieved value is NULL (as NULL is different from empty space "", try to look at the previous discussion here)
However to perform what you would like to achieve I have written a short code as follows.
var tr = $('#table1 tr');
var index = 0;
for(i = tr.length - 1; i > 0; i--) {
if($(tr[i]).find('td:eq(1)').html() != "") {
index = i;
break;
}
}
console.log(index);
Basically what it does is that it will find the table's tr and compare line by line to check the 2nd column td:eq(1) to see whether the raw HTML value is empty (sorry but I would like to emphsize again it is not a very good comparison method) and return the value.
I have not optimize the code based on the performance but I think it should be suffice in achieving what you would like to do.
Hope this helps.
Regards.

Removing elements by ID

I have a table with the following structure:
<table>
<tr>
<td>some column|1</td>
<td id="abc|1">abc</td>
<td id="abc|1">abc</td>
</tr>
<tr>
<td>another column|1</td>
<td id="def|1">def</td>
<td id="def|1">def</td>
</tr>
<tr>
<td>ome column|2</td>
<td id="abc|2">abc</td>
<td id="abc|2">abc</td>
</tr>
<tr>
<td>another column|2</td>
<td id="def|2">def</td>
<td id="def|2">def</td>
</tr>
</table>
The content comes from a database.
As you can see, the IDs have the suffix |x. I want to remove all elements with the suffix |2 in the 2nd column and all elements with the suffix |1 in the 3rd column.
Also the 3rd column should be shifted to the top, and all rows ending with |2 in the 1st column should disappear.
So that the final result looks like that:
<table>
<tr>
<td>some column|1</td>
<td id="abc|1">abc</td>
<td id="abc|2">abc</td>
</tr>
<tr>
<td>another column|1</td>
<td id="def|1">def</td>
<td id="def|2">def</td>
</tr>
</table>
This is my approach, but it doesn't work at all:
$("table td:nth-child(2)").find("[id$=2]").each(function() {
$(this).hide();
});
$("table td:nth-child(3)").find("[id$=1]").each(function() {
$(this).hide();
});
Here is the fiddle.
ID should be unique. It's better if you can change the HTML and make IDs unique.
IF CHANGING HTML IS NOT POSSIBLE
As both the selector are pointing to same element, use following
$("table td:nth-child(2)[id$=2], table td:nth-child(3)[id$=1]").hide();
Demo

Categories