Javascript Filtering by multiple columns - javascript

Borrowing code from the post below I am able to filter on 2 columns using the || (Or) operator.
However, I'd like to be able to filter using the && (And) operator.
I have been unsuccessful in my multiple attempts. I could use some help.
Filtering table multiple columns
function myFunction() {
var input0, input1, filter0, filter1, table, tr, td, cell, i, j;
document.getElementById("myInput0").value = 'Female';
document.getElementById("myInput1").value = 'Engineering';
input0 = document.getElementById("myInput0");
input1 = document.getElementById("myInput1");
filter0 = input0.value.toUpperCase();
filter1 = input1.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 1; i < tr.length; i++) {
// Hide the row initially.
tr[i].style.display = "none";
td = tr[i].getElementsByTagName("td");
for (var j = 0; j < td.length; j++) {
cell = tr[i].getElementsByTagName("td")[j];
if (cell) {
if (cell.textContent.toUpperCase().indexOf(filter0)>-1 ||
cell.textContent.toUpperCase().indexOf(filter1)>-1) {
tr[i].style.display = "";
break;
}
}
}
}
}
<body>
<input type="text" id="myInput0">
<input type="text" id="myInput1">
<input type='button' onclick='myFunction()' value='click me' />
<table id="myTable">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Gender</th>
<th>Department</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>Male</td>
<td>Sales</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>Female</td>
<td>Service</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>Female</td>
<td>Service</td>
</tr>
<tr>
<td>Anja</td>
<td>Ravendale</td>
<td>Female</td>
<td>Engineering</td>
</tr>
<tr>
<td>Thomas</td>
<td>Dubois</td>
<td>Male</td>
<td>Sales</td>
</tr>
<tr>
<td>Deidre</td>
<td>Masters</td>
<td>Female</td>
<td>Sales</td>
</tr>
<tr>
<td>Sean</td>
<td>Franken</td>
<td>Male</td>
<td>Engineering</td>
</tr>
</tbody>
</table>
</body>

For each cell, you can check each filter separately, then only change the DOM for rows where all filter conditions are met.
(This example uses a restructured version of your code.)
document.getElementById("myInput0").value = 'Female';
document.getElementById("myInput1").value = 'Engineering';
const
input0 = document.getElementById("myInput0"),
input1 = document.getElementById("myInput1"),
table = document.getElementById("myTable"),
rows = table.getElementsByTagName("tr");
function myFunction() {
filter0 = input0.value.toUpperCase(),
filter1 = input1.value.toUpperCase();
for (let row of rows) {
row.classList.add("hidden");
const cells = row.getElementsByTagName("td");
let
filter0met = false,
filter1met = false;
for (let cell of cells) {
if (cell.textContent.toUpperCase().includes(filter0)) {
filter0met = true;
}
if (cell.textContent.toUpperCase().includes(filter1)) {
filter1met = true;
}
}
if (filter0met && filter1met) {
row.classList.remove("hidden");
}
}
}
.hidden {
display: none;
}
<body>
<input type="text" id="myInput0"><input type="text" id="myInput1"><input type='button' onclick='myFunction()' value='click me' />
<table id="myTable">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Gender</th>
<th>Department</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>Male</td>
<td>Sales</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>Female</td>
<td>Service</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>Female</td>
<td>Service</td>
</tr>
<tr>
<td>Anja</td>
<td>Ravendale</td>
<td>Female</td>
<td>Engineering</td>
</tr>
<tr>
<td>Thomas</td>
<td>Dubois</td>
<td>Male</td>
<td>Sales</td>
</tr>
<tr>
<td>Deidre</td>
<td>Masters</td>
<td>Female</td>
<td>Sales</td>
</tr>
<tr>
<td>Sean</td>
<td>Franken</td>
<td>Male</td>
<td>Engineering</td>
</tr>
</tbody>
</table>
</body>

After much trial and error for I was able to put together some JQuery that will dynamically search the first input, and then search those results for the second input. Note, I am using SP2016. While I've included it here in my post, I could not get the call to "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" to work. I found downloading and storing the file on my SharePoint site worked. For my requirement I wanted to display my list with grouped rows so I'm using a function to collapse the groups on load. The caveat is the groups in listview have to be configured as expanded.
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!DOCTYPE html>
<html>
<head>
<SCRIPT type="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></SCRIPT>
<script>
//If rows are not grouped, remove this function
$(window).load(function () {
$(".ms-commentcollapse-icon").click();
});
$(document).ready(function() {
$("#myInput").on("keyup", function() {
var value = this.value.toLowerCase();
//If rows are not grouped, remove this line
$(".ms-commentexpand-icon").click();
$('.ms-listviewtable > tbody > tr').addClass('myInputMismatch').filter(function() {
return this.innerHTML.toLowerCase().indexOf(value) > -1;
}).removeClass('myInputMismatch');
});
$("#myInput1").on("keyup", function() {
var value = this.value.toLowerCase();
$('.ms-listviewtable > tbody > tr').addClass('myInput1Mismatch').filter(function() {
return this.innerHTML.toLowerCase().indexOf(value) > -1;
}).removeClass('myInput1Mismatch');
});
});
</script>
<style>
.myInputMismatch, .myInput1Mismatch { display: none; }
</style></head>
<input id="myInput" type="text" Placeholder="Search here 1st..."><input id="myInput1" type="text" Placeholder="Search here 2nd...">

Related

I'm trying to make a function in JS to search the <td> tags in an HTML table but it doesn't work if I use any <th></th> tags in it

EDIT: Nevermind, I just fixed my problem by making the header a separate table to hold all of my tags
So I have a HTML table and I want to have a search bar to search the table because it's pretty large. I tried copying the code from this W3 schools tutorial (https://www.w3schools.com/howto/howto_js_filter_lists.asp) and I got it modified and working for the table, but only if I don't use any rows that include tags.
Here's my currently working code (I commented out the code segment that was giving me trouble):
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<table id="myUL" class="BuyBooksTable">
<!--<tr>
<th colspan="3">Books</th>
</tr>
<tr>
<th>Item</th>
<th>Price</th>
<th>Purchase Item</th>
</tr> -->
<div id="myULSmaller">
<tr>
<td>Alice</td>
<td>Price</td>
<td>Purchase Item</td>
</tr>
<tr>
<td>Bob</td>
<td>Price</td>
<td>Purchase Item</td>
</tr>
<tr>
<td>Carol</td>
<td>Price</td>
<td>Purchase Item</td>
</tr>
</div>
</table>
<script>
function myFunction() {
// Declare variables
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName('tr');
// Loop through all list items, and hide those who don't match the search query
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("td")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
</script>
Using querySelectorAll.
Also, you can use <tbody> rather than to have a div inside your table.
function myFunction(e) {
let searchTerm = e.value.toLocaleLowerCase();
var trs = document.querySelectorAll('table tbody tr');
[].forEach.call(trs, function(tr) { // all trs
[].forEach.call(tr.children, function(td) { // all tds
if (td.getAttribute('search')) { // check if the td needs to be considers for search criteria
if (td.innerText.toLocaleLowerCase().includes(searchTerm)) {
tr.style.display = "";
} else {
tr.style.display = "none";
}
}
});
});
}
<input type="text" id="myInput" onkeyup="myFunction(this)" placeholder="Search for names.." title="Type in a name">
<table id="myUL" class="BuyBooksTable">
<tr>
<th colspan="3">Books</th>
</tr>
<tr>
<th>Item</th>
<th>Price</th>
<th>Purchase Item</th>
</tr>
<tbody>
<tr>
<td search="true">Alice</td>
<td>Price</td>
<td>Purchase Item</td>
</tr>
<tr>
<td search="true">Bob</td>
<td>Price</td>
<td>Purchase Item</td>
</tr>
<tr>
<td search="true">Carol</td>
<td>Price</td>
<td>Purchase Item</td>
</tr>
</tbody>
</table>
You need to check that the value a in the line a = li[i].getElementsByTagName("td")[0]; exists. Try this:
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<table id="myUL" class="BuyBooksTable">
<tr>
<th colspan="3">Books</th>
</tr>
<tr>
<th>Item</th>
<th>Price</th>
<th>Purchase Item</th>
</tr>
<div id="myULSmaller">
<tr>
<td>Alice</td>
<td>Price</td>
<td>Purchase Item</td>
</tr>
<tr>
<td>Bob</td>
<td>Price</td>
<td>Purchase Item</td>
</tr>
<tr>
<td>Carol</td>
<td>Price</td>
<td>Purchase Item</td>
</tr>
</div>
</table>
<script>
function myFunction() {
// Declare variables
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName('tr');
// Loop through all list items, and hide those who don't match the search query
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("td")[0];
//If a doesn't exist, carry on looping:
if (!a) {
continue;
}
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
</script>
just use :nth-child(n+3) selector
document.querySelectorAll('#myUL tr:nth-child(n+3)')
or edit your code like
...
//ul = document.getElementById("myUL");
ul = document.getElementById("myULSmaller");
...
or use this
let trs = document.querySelectorAll('#myUL tr:nth-child(n+3)');
function myFunction() {
let filter = this.value.trim().toLowerCase();
let emptyStr = filter.length == 0;
trs.forEach(function(el) {
el.style.display = emptyStr || el.textContent.toLowerCase().includes(filter)?"":"none";
});
}
Nidhins answer is great but if you need to search all columns you need to modify it.
I include a variable to track if any cell in the row matches. Highlite that cell and display the row
//Set event listener
document.getElementById("myInput").addEventListener("keyup",function(){
var normalisedSearch = this.value.toLocaleLowerCase();
//Grab the search tr in the table body
var searchTrs = document.querySelectorAll("#myUL>tbody>tr");
//iterate the cells in the tr
[].forEach.call(searchTrs,function(tr){
var visible = false;
//iterate the cells in the row
var searchTds = tr.querySelectorAll("td");
[].forEach.call(searchTds, function(td){
if(td.innerText.toLocaleLowerCase().includes(normalisedSearch)){
visible = true;
td.style.backgroundColor = normalisedSearch !== "" ? "#CCC" : "";
}else{
td.style.backgroundColor = "";
}
});
//Sit vidibility of the row
tr.style.display = visible ? "" : "none";
});
});
<input type="text" id="myInput" placeholder="Search for names.." title="Type in a name">
<table id="myUL" class="BuyBooksTable">
<tr>
<th colspan="3">Books</th>
</tr>
<tr>
<th>Item</th>
<th>Price</th>
<th>Purchase Item</th>
</tr>
<tbody>
<tr>
<td>Alice</td>
<td>20</td>
<td>Purchase Item</td>
</tr>
<tr>
<td>Bob</td>
<td>15</td>
<td>Purchase Item</td>
</tr>
<tr>
<td>Carol</td>
<td>2</td>
<td>Purchase Item</td>
</tr>
</tbody>
</table>

JS - Compare first row to other rows in table

I'm a completely newbie and looking for help.
Given the following table:
<table id="table">
<thead>
# FIRST ROW
<tr>
<th>Apple</th>
<th>Pizza</th>
<th>Eggs</th>
</tr>
<tbody>
# SECOND ROW
<tr>
<td>Apple</td> --> should end with 'success' class
<td>Juice</td>
<td>Lettuce</td>
<td>Oranges</td>
<td>Eggs</td> --> should end with 'success' class
</tr>
# THIRD ROW
<tr>
<td>Pizza</td> --> should end with 'success' class
<td>Chicken</td>
</tr>
</tbody>
</table>
I would like to add class 'success' to every td in SECOND and THIRD rows whenever it matches any td in FIRST row (and only in FIRST ROW).
For now I came up with adding <td> values of first row to array and I'm not sure what steps should I take next (filter? for loop and '===' comparison?):
function myFunction() {
var tHeadersValues = [];
var tHeaders = document.getElementById("table").rows[0].cells;
for (var i = 0; i < tHeaders.length; i++) {
tHeadersValues.push(tHeaders[i].textContent);
}
return tHeadersValues;
}
Object.keys(tHeaders).map(key => tHeaders[key].textContent) transforms the td objects to an array with the containing text. The rest is straight forward:
function toValues(tHeaders) {
return Object.keys(tHeaders).map(function(key){
return tHeaders[key].textContent;
});
}
function myFunction() {
var rows = document.getElementById("results-table").rows;
var tHeadersValues = toValues(rows[0].cells);
for (var i = 1; i < rows.length; i++) {
var rowCells = rows[i].cells;
var values = toValues(rowCells);
for(var j=0;j<values.length;j++) {
if(values[j].length > 0 && tHeadersValues.indexOf(values[j]) > -1) {
rowCells[j].className = "success";
}
}
}
}
myFunction();
<style>
.success {
background-color: green;
}
</style>
<table id="results-table">
<thead>
<tr>
<th>Apple</th>
<th>Pizza</th>
<th>Eggs</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Juice</td>
<td>Lettuce</td>
<td>Oranges</td>
<td>Eggs</td>
</tr>
<tr>
<td>Pizza</td>
<td>Chicken</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
function myFunc(){
var tds = document.getElementsByTagName("td");
var hds = document.getElementsByTagName("th");
for(var i=0; i<tds.length; i++) {
var tdContent = tds[i].innerHTML;
if(tdContent.length > 0){
for(var j = 0; j<hds.length; j++) {
if(tdContent === hds[j].innerHTML) {
document.getElementsByTagName("td")[i].className = "success";
}
}
}
}
}
myFunc();
<style>
.success {
background-color: green;
}
</style>
<table id="results-table">
<thead>
<tr>
<th>Apple</th>
<th>Pizza</th>
<th>Eggs</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>Juice</td>
<td>Lettuce</td>
<td>Oranges</td>
<td>Eggs</td>
</tr>
<tr>
<td>Pizza</td>
<td>Chicken</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>

Loop HTML table and add the identical items and its calculated amount to another table

<html>
<body>
<div>
<table border="1" id="topTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="topTableBody">
<tr>
<td>Apples</td>
<td>50</td>
</tr>
<tr>
<td>Apples</td>
<td>25</td>
</tr>
<tr>
<td>Oranges</td>
<td>30</td>
</tr>
<tr>
<td>Strawberry</td>
<td>60</td>
</tr>
<tr>
<td>Cherry</td>
<td>10</td>
</tr>
<tr>
<td>Guava</td>
<td>5</td>
</tr>
<tr>
<td>Strawberry</td>
<td>20</td>
</tr>
</tbody>
</table>
</div>
<button id="btn">Click</button>
</br>
<div>
<table border="1" id="bottomTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="bottomTableBody">
</tbody>
</table>
</div>
</body>
</html>
When I press on the button I want it to loop through the top table and get the item names that're alike and add them in one row with the sold amount combined in the bottom table ex: apples will have their own row with a sold amount of 75 and others who have no names that're alike will have their own row such as Oranges with the sold amount also.
If you can use JQuery.
(JSFiddle: http://jsfiddle.net/inanda/o9axgkaz/):
jQuery('#btn').on('click', function() {
var sumMap = {};
//Iterate through table rows
$("table tbody tr").each(function () {
if (sumMap[$(this).children('td:nth-child(1)').text()]) {
sumMap[$(this).children('td:nth-child(1)').text()] = sumMap[$(this).children('td:nth-child(1)').text()] +Number($(this).children('td:nth-child(2)').text());
} else {
sumMap[$(this).children('td:nth-child(1)').text()] = Number($(this).children('td:nth-child(2)').text());
}
})
//Append result to the other table
$.each(sumMap, function (i, val) {
$('#bottomTable tr:last').after('<tr><td>'+i+'</td><td>'+val+'</td>');
});
});
Pure javascript:
(JSFiddle: http://jsfiddle.net/inanda/2dmwudfj/ ):
appendResultToBottomTable= function() {
var sumMap = calculate();
appendResultToTable('bottomTableBody', sumMap);
}
function calculate() {
var table = document.getElementById("topTableBody");
var map = {};
for (var i = 0, row; row = table.rows[i]; i++) {
var itemType=(row.cells[0].innerText || row.cells[0].textContent);
var value=(row.cells[1].innerText || row.cells[1].textContent);
if (map[itemType]) {
map[itemType] = map[itemType] +Number(value);
} else {
map[itemType] = Number(value);
}
}
return map;
}
function appendResultToTable(tableId, sumMap){
var table = document.getElementById(tableId);
for (var item in sumMap){
var row = table.insertRow(table.rows.length);
var cellItem = row.insertCell(0);
var cellValue = row.insertCell(1);
cellItem.appendChild(document.createTextNode(item));
cellValue.appendChild(document.createTextNode(sumMap[item]));
}
}
If it is applicable for your project to use external libraries, you can do it with code like below:
alasql('SELECT Item,SUM(CONVERT(INT,Sold)) AS Sold \
INTO HTML("#res",{headers:true}) \
FROM HTML("#topTable",{headers:true}) \
GROUP BY Item');
Here:
SELECT Item, SUM(Sold) FROM data GROUP BY Item is a regular SQL expression to group and sum data from the table
CONVERT(INT,Sold) conversion procedure from string to INT type
FROM HTML() and INTO HTML() special functions to read/write data from/to HTML table, {headers:true} is a parameter to use headers
I added some minor CSS code (for table and cells borders), because Alasql generates the "plain" HTML table.
See the working snippet below.
(Disclaimer: I am an author of Alasql library)
function run() {
alasql('SELECT Item,SUM(CONVERT(INT,Sold)) AS Sold INTO HTML("#res",{headers:true}) FROM HTML("#topTable",{headers:true}) GROUP BY Item');
}
#res table {
border:1px solid black;
}
#res table td, th{
border:1px solid black;
}
<script src="http://alasql.org/console/alasql.min.js"> </script>
<div>
<table border="1" id="topTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="topTableBody">
<tr>
<td>Apples</td>
<td>50</td>
</tr>
<tr>
<td>Apples</td>
<td>25</td>
</tr>
<tr>
<td>Oranges</td>
<td>30</td>
</tr>
<tr>
<td>Strawberry</td>
<td>60</td>
</tr>
<tr>
<td>Cherry</td>
<td>10</td>
</tr>
<tr>
<td>Guava</td>
<td>5</td>
</tr>
<tr>
<td>Strawberry</td>
<td>20</td>
</tr>
</tbody>
</table>
</div>
<button id="btn" onclick="run()">Click</button>
</br>
<div id="res"></div>

How to copy the contents of one row in a table to another table and add the identical ones

var Sell_Button = document.getElementById('sellbtn'),
secondTable = document.getElementById("secondTableBody");
Sell_Button.addEventListener('click', function() {
var Row = secondTable.insertRow();
for (var c = 0; c < 2; c += 1) {
Row.insertCell(c);
}
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[2].innerHTML = this.parentNode.parentNode.cells[1].innerHTML;
//checks to see if the secondTable has a row containing the same name
for (var f = 0; f < secondTable.rows.length; f += 1) {
//adds only the sold amount if the second table has a row with the same name
//error
if (secondTable.rows[f].cells[0].innerText === this.parentNode.parentNode.cells[0].innerText) {
secondTable.rows[f].cells[1].innerHTML = +this.parentNode.parentNode.cells[2].innerHTML;
//deletes an extra row that is added at the bottom
if (secondTable.rows.length > 1) {
secondTable.deleteRow(secondTable.rows.length - 1);
}
//if nothing matched then a new row is added
} else {
secondTable.insertRow();
Row.cells[0].innerHTML = this.parentNode.parentNode.cells[0].innerHTML;
Row.cells[1].innerHTML = this.parentNode.parentNode.cells[2].innerHTML;
}
}
}
}
<html>
<body>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td>
<button id="sellbtn">Sell</button>
</td>
</tr>
</tbody>
</table>
</div>
</br>
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTableBody">
</tbody>
</table>
</div>
</body>
</html>
Ok, this example isn't exactly what i'm working on but it's very similar. The only difference is that in mine the rows and buttons are dynamically added by the user and he inserts the details. What I want is that when i press on the button of each row (sell) the details (Item and Sold only) are copied into a row in the second table and checks if the same item exists in this second table if so then it adds the amount of sold of both items in one row. For instance I press on the first row button the Apples it copies the listed above details to the second table in a row and then when i click on the button of the second row (Apples also) it only adds the sold amount up and doesn't add a second apples row because an apples row already exists in the second table but when i click on the oranges button it makes a new row because the oranges row doesn't exist. So how do I do this in JavaScript? i hope i was thorough and made any sense. I have no idea why the code isn't working here but i hope you get the point. This code works perfectly just as i want it to until for some reason i get this error: Cannot read property 'innerText' of undefined when i press the buttons approx. 6-7 times targeting the if statement where i commented error.
This sets a click handler to all buttons. If the row doesn't exist in the second table it's created. It sets a data-type referring to the item. When somebody clicks the sell button again and there is a row containing the data-type the row is updated instead of created. All in plain JavaScript.
var Sell_Button = document.querySelectorAll('.sellbtn'),
secondTable = document.getElementById("secondTableBody");
Array.prototype.slice.call(Sell_Button).forEach(function(element){
element.addEventListener('click', function(e) {
//since the button is an element without children use e.
var clickedElement = e.target;
var parentRow = clickedElement.parentNode.parentNode;
//check if second table has a row with data-type
var rowWithData = secondTable.querySelector("[data-type='"+parentRow.cells[0].childNodes[0].nodeValue+"']");
if (rowWithData)
{
rowWithData.cells[1].innerHTML = parseInt(rowWithData.cells[1].childNodes[0].nodeValue) + parseInt(parentRow.cells[2].childNodes[0].nodeValue);
}
else
{
var Row = secondTable.insertRow();
Row.setAttribute("data-type", parentRow.cells[0].childNodes[0].nodeValue);
for (var c = 0; c < 2; c += 1) {
Row.insertCell(c);
}
Row.cells[0].innerHTML = parentRow.cells[0].childNodes[0].nodeValue;
Row.cells[1].innerHTML = parentRow.cells[2].childNodes[0].nodeValue;
}
});
});
<html>
<body>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td>
<button class="sellbtn">Sell</button>
</td>
</tr>
</tbody>
</table>
</div>
</br>
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="secondTableBody">
</tbody>
</table>
</div>
</body>
</html>
Do you mean something like:
$(document).on("click", "#firstTable tr button", function(b) {
b = $(this).closest("tr");
var d = $.trim(b.find("td:first").text());
b = parseFloat($.trim(b.find("td:nth-child(3)").text()));
var a = $("#secondTable"),
c = a.find("tr").filter(function(a) {
return $.trim($(this).find("td:first").text()) == d
});
c.length ? (a = c.find("td:nth-child(2)"), c = parseFloat($.trim(a.text())), a.text(b + c)) : (a = $("<tr />").appendTo(a), $("<td />", {
text: d
}).appendTo(a), $("<td />", {
text: b
}).appendTo(a))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="firstTableDiv">
<table border="1" id="firstTable">
<thead>
<tr>
<th>Item</th>
<th>Stock</th>
<th colspan="1">Sold</th>
</tr>
</thead>
<tbody id="firstTableBody">
<tr>
<td>Apples</td>
<td>300</td>
<td>200</td>
<td><button>Sell</button></td>
</tr>
<tr>
<td>Apples</td>
<td>300</td>
<td>100</td>
<td><button>Sell</button></td>
</tr>
<tr>
<td>Oranges</td>
<td>400</td>
<td>300</td>
<td><button>Sell</button></td>
</tr>
</tbody>
</table>
</div>
<br />
<div id="secondTableDiv">
Sold
<table border="1" id="secondTable">
<thead>
<tr>
<th>Item</th>
<th>Sold</th>
</tr>
</thead>
<tbody id="secondTableBody"></tbody>
</table>
</div>

Sorting pairs of rows with tablesorter

http://jsfiddle.net/9sKwJ/66/
tr.spacer { height: 40px; }
$.tablesorter.addWidget({
id: 'spacer',
format: function(table) {
var c = table.config,
$t = $(table),
$r = $t.find('tbody').find('tr'),
i, l, last, col, rows, spacers = [];
if (c.sortList && c.sortList[0]) {
$t.find('tr.spacer').removeClass('spacer');
col = c.sortList[0][0]; // first sorted column
rows = table.config.cache.normalized;
last = rows[0][col]; // text from first row
l = rows.length;
for (i=0; i < l; i++) {
// if text from row doesn't match last row,
// save it to add a spacer
if (rows[i][col] !== last) {
spacers.push(i-1);
last = rows[i][col];
}
}
// add spacer class to the appropriate rows
for (i=0; i<spacers.length; i++){
$r.eq(spacers[i]).addClass('spacer');
}
}
}
});
$('table').tablesorter({
widgets : ['spacer']
});
<table id="test">
<thead>
<tr>
<th>Name</th>
<th>Number</th>
<th>Another Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>Test4</td>
<td>4</td>
<td>Hello4</td>
</tr>
<tr>
<td colspan="3">Test4</td>
</tr>
<tr>
<td>Test3</td>
<td>3</td>
<td>Hello3</td>
</tr>
<tr>
<td colspan="3">Test3</td>
</tr>
<tr>
<td>Test2</td>
<td>2</td>
<td>Hello2</td>
</tr>
<tr>
<td colspan="3">Test2</td>
</tr>
<tr>
<td>Test1</td>
<td>1</td>
<td>Hello1</td>
</tr>
<tr>
<td colspan="3">Test1</td>
</tr>
</tbody>
</table>
This sorts just the way I want it if you sort it by the first column, but the other two columns don't maintain the same paired 'tr' sort im looking for.
Any help on this?
Use the expand-child class name on each duplicated row:
<tr>
<td>Test3</td>
<td>3</td>
<td>Hello3</td>
</tr>
<tr class="expand-child">
<td colspan="3">Test3</td>
</tr>
It's defined by the cssChildRow option:
$('table').tablesorter({
cssChildRow: "expand-child"
});​
Here is a demo of it in action.

Categories

Resources