javascript - Sorting Table with Hierarchical Data -
i have odd situation have html table hierarchical data , need provide ability sort data, "parent" rows, not children. in fact, children should stay attached parent, wherever parent gets sorted, children should follow along (but don't have sorted internally). example:

when click on "rating", should sort bolded ratings , children (the weeds in example) should go along ride. there magical jquery plugin me? :)
edit here stripped-down version of rendered html. have amount of control on this, not (the markup comes remote endpoint...).
<table id="grid"> <thead> <tr role="row"> <th>name</th> <th>rating</th> <th>timing</th> </tr> </thead> <tbody> <tr> <td><b>butyrac 200</b></td> <td><b>8</b></td> <td>post</td> <td>3</td> </tr> <tr> <td>common chickweed</td> <td>4</td> <td></td> <td></td> </tr> <tr> <td>common dandelion</td> <td>4</td> <td></td> <td></td> </tr> <tr> <td><b>chateau</b></td> <td><b>14</b></td> <td>pre</td> <td>6</td> </tr> <tr> <td>common chickweed</td> <td>10</td> <td></td> <td></td> </tr> <tr> <td>common dandelion</td> <td>4</td> <td></td> <td></td> </tr> </tbody>
if have in matter, ask have bit more structure/definition added markup can rely on data rather presentation determine how these rows related.
as is, looks need rely on elements of presentation being present. can brittle coming along later , changing presentation can break logic quickly.
here i've made assumption top level rows have <b> marker - may need adjust depending on exact requirements.
no magic here, bit of elbow grease:
var $tbody = $('#grid > tbody'); var toprows = []; var children = []; $tbody.find('tr').each(function (idx, ele) { var $ele = $(ele); if ($ele.find('td:eq(0) > b').length) { // it's parent // make new parent var newparent = { ele: $ele, children: [] }; toprows.push(newparent); // keep track of children children = newparent.children; } else { // it's child children.push($ele); } }); // sort top level array value of rating td toprows.sort(function(topa, topb) { var vala = +topa.ele.find('td:eq(1) > b').text(); var valb = +topb.ele.find('td:eq(1) > b').text(); return vala - valb; }); // detach temporarily avoid live dom updates $tbody.detach().empty(); // add newly sorted parents in along children $.each(toprows, function(topidx, top) { $tbody.append(top.ele); $.each(top.children, function(childidx, child) { $tbody.append(child); }); }); $('#grid').append($tbody);
Comments
Post a Comment