Drag n drop - save the reorder of rows
HTML
<table class="fooBar" width="200">
<thead>
<tr style="background-color:#ccc">
<td><b>ColHeader1</b></td>
<td><b>ColHeader2</b></td>
<td><b>ColHeader3</b></td>
</tr>
</thead>
<tbody>
<tr class="section1 subhead">
<td><b>Section1</b></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>CellData</td>
<td>CellData</td>
<td>CellData</td>
</tr>
<tr>
<td>CellData</td>
<td>CellData</td>
<td>CellData</td>
</tr>
</tbody>
<tbody>
<tr class="section2 subhead">
<td><b>Section2</b></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>CellData</td>
<td>CellData</td>
<td>CellData</td>
</tr>
<tr>
<td>CellData</td>
<td>CellData</td>
<td>CellData</td>
</tr>
</tbody>
<tbody>
<tr class="section3 subhead">
<td><b>Section3</b></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>CellData</td>
<td>CellData</td>
<td>CellData</td>
</tr>
<tr>
<td>CellData</td>
<td>CellData</td>
<td>CellData</td>
</tr>
</tbody>
</table>
CSS
.ui-sortable-helper {
display: table;
}
.selected {
color: white
}
.section1 {
background: blue
}
.section2 {
background: green
}
.section3 {
background: orange
}
.section1 ~ tr {
background: blue
}
.section2 ~ tr {
background: green
}
.section3 ~tr {
background: orange
}
JavaScript
$(function() {
$(".fooBar tbody").sortable({
connectWith: ".fooBar tbody",
items: '>tr:not(.subhead)',
cursor: "move",
axis: 'y',
start: function(e, ui) {
ui.item.addClass("selected");
},
stop: function(e, ui) {
ui.item.removeClass("selected");
saveOrder()
},
}).each(function(tbodyNumber, tbody) {
$(this).attr("id", tbodyNumber)
$(this).children().each(function(rowNumber, row) {
$(this).attr("id", tbodyNumber + "-" + rowNumber);
})
})
reOrder()
})
function saveOrder() {
var mapping = {}
$(".fooBar tbody").each(function() {
var key = $(this).attr("id")
var data = $(this).children().map(function() {
return $(this).attr("id")
}).get()
mapping[key] = data
})
localStorage.order = JSON.stringify(mapping)
}
function reOrder() {
$.each(JSON.parse(localStorage.order)||[],function(tbodyNumber,kids){
console.log(tbodyNumber,kids)
$.each(kids,function(i,id){
$("#"+id).appendTo("#"+tbodyNumber)
})
})
}