I need to move a table row from a position to the first in the table and after clicking again to the old position.
I have a list of checkboxes in a table. These are coming from code behind and are already sorted. If I click on a checkbox, I want to move this entry to the begin of the list. If the users unchecks this box or clicks on another box, it shall be moved to the old position.
for better understanding:
[ ] 1
[ ] 3
[ ] A
[ ] B
[ ] C
After clicking on e.g. [ ] C
:
[X] C
[ ] 1
[ ] 3
[ ] A
[ ] B
After clicking on e.g. [ ] 3
C has got the old position and 3 has moved to the top.
[X] 3
[ ] 1
[ ] A
[ ] B
[ ] C
I've managed to get a row to the top. But how do I move a row again to the old position?
example with working code for moving to top:
I would store each tr's position and move it back if/when needed.
I updated the code according to ShadowScripter's comment
New update http://jsfiddle.net/gguNM/2/
$('table tr').each(function () {
var $this = $(this).data({position: $(this).index()}),
$table = $this.closest('table'),
$input = $this.find('input');
$input.bind('click', function (e) {
var $first = $table.find('tr:first'),
position;
if ($(this).is(':checked')) {
position = $first.data('position');
$table.find('tr input').not($(this)).removeAttr('checked');
if (position != 0) $first.insertAfter($table.find('tr').eq(position));
$this.prependTo($table);
} else if ($this.data('position') != 0) {
position = $this.data('position');
$this.insertAfter($table.find('tr').eq(position));
}
});
});