Sort a table with child rows

I know this can be tricky, but I was aiming for a solution without any luck, so I have a table with expandable / compressible rows / child rows:

Col1 Col2 Col3 Node AAA --A child 1 A1 A1 --A child 2 Foo Bar Node B Foo Bar --B child 1 B1 B1 --B child 2 Foo Bar 

So, while all the child lines are expanded, and I sort Col1, I expect that sorting Node A and Node B, NOT will sort all child lines, i.e. if col1 collation, i should see this:

 Col1 Col2 Col3 Node B Foo Bar --B child 1 B1 B1 --B child 2 Foo Bar Node AAA --A child 1 A1 A1 --A child 2 Foo Bar 

Not this....:

 Col1 Col2 Col3 --B child 1 B1 B1 --B child 2 Foo Bar --A child 1 A1 A1 --A child 2 Foo Bar Node B Foo Bar Node AAA 

My code is located at https://jsfiddle.net/wayneye/tyxykyf3/ , I used the jQuery sorter , but can't restrict its use until my requirement is met: sort the parent rows, not the child rows

Please kindly give me a hand, you can change my HTML / js structure or use other libraries, appreciated!

+6
source share
2 answers

If you check this link here , it states the following (for tablesorter 2.15.12+, and you are using 2.25.4):

Parents of child rows now have the class name tablesorter-hasChildRow added.

If you look at the example on this page, you will also notice that there is a class for the child rows of tablesorter-childRow .

You just need to add tablesorter-hasChildRow to the parent rows and tablesorter-childRow to your child rows.

Updated JSFiddle Here

+5
source

In vanilla JS, you can simply write a sort function in a string collection. You also need to add id to the parent lines of the form id="A-parent" for my specific solution:

Fiddle: https://jsfiddle.net/vcbq843o/2/

JS:

 var sortTable = function (ascending) { var tableBody = document.querySelector('#tb > tbody'); //Get the rows as a native js array. var rows = Array.prototype.slice.call(tableBody.querySelectorAll('tr')); //Native js sort function. rows.sort(function(first,second){ //The difference between char codes lets us sort alphabetically. //If they have the same code, they will be left in the same order. //This means that the children will still be in the same relative position. var posFirst = first.id.charCodeAt(0); var posSecond = second.id.charCodeAt(0); //Subtract, based on whether we want ascending or descending. return ascending ? posSecond - posFirst : posFirst - posSecond; }); //Add the rows back to the table in our new order. for(var i=0; i<rows.length; i++) { tableBody.appendChild(rows[i]); } } 
0
source

All Articles