I know this might be tricky, but I have been strived for a solution with no luck, so I have a table with expandable/collapsable row/child-rows:
Col1 Col2 Col3 Node A A A --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 child-rows got expanded and I am sorting Col1, I am expecting to sort Node A and Node B, NOT sort all the child rows, i.e., if sort Col1, I should see this:
Col1 Col2 Col3 Node B Foo Bar --B child 1 B1 B1 --B child 2 Foo Bar Node A A A --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 A A A My code is located at: https://jsfiddle.net/wayneye/tyxykyf3/, I was using jquery table sorter, but don't restrict to use it as long as my requirement satisfied: sort the parent rows, not child-rows
Please kindly give me a hand, you can change my HTML structure/js, or using other libs, appreciated!
2 Answers
Answers 1
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 a tablesorter-hasChildRow class name added.
If you look at the example on that page, you will also note that there is a class for child rows tablesorter-childRow.
You simply need to add tablesorter-hasChildRow to your parent rows, and tablesorter-childRow to your child rows.
Answers 2
In vanilla JS, you can just write a sort function on a collection of the rows. You'd also have to add an id to the parent rows of the form id="A-parent" for my particular 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 comments:
Post a Comment