I'm trying to work out how to move rows and set an ordering value against them.
I've got quite a simple table layout. The data is being passed from a backend management system which I have no control over.
My table ends up looking like this:
<table id='sites'>
<tr id="0" data-site="SITE:1" data-order="1" data-siteid="12456232" class="site_heading nodrag"><td>SITE1
<td><span id='up'>Up</span> / <span id='down'>Down</span></td></tr>
<tr id="5" data-site="SITE:3" data-order="3" data-siteid="78565213" class="site_heading nodrag"><td>SITE3
<td><span id='up'>Up</span> / <span id='down'>Down</span></td></tr>
<tr id="8" data-site="SITE:4" data-order="4" data-siteid="36587492" class="site_heading nodrag"><td>SITE4
<td><span id='up'>Up</span> / <span id='down'>Down</span></td></tr>
<tr id="6" data-site="SITE:2" data-order="2" data-siteid="02365874" class="site_heading nodrag"><td>SITE2
<td><span id='up'>Up</span> / <span id='down'>Down</span></td></tr>
</table>
The rows I'm showing are section rows, there may be other rows in the table but these are the only ones I'm currently interested in .
Each row has a unique ID, a data-site and a data-order. As the information can be passed to the script in any order, I'm using the following to sort the rows using the data-order attribute :
var $table=$('#sites');
var rows = $table.find('tr.site_heading').get();
rows.sort(function(a, b) {
var keyA = $(a).attr('data-order');
var keyB = $(b).attr('data-order');
if (!keyA || !keyB) return -1;
if (keyA > keyB) return 1;
if (keyA < keyB) return -1;
return 0;
});
This can be seen working HERE
Each row needs to be able to move up order down the table and then have it's data-order updated. This is quite simple as I'm only moving one row at a time effectivity swapping two rows positions.
If I move a row up I swap the data-order value with the row it's moved above and if I move a row down I swap it's data-order with the row it's moved below.
All this works great... Until I get rows with NO data-order value.
These rows don't get ordered onload as there is no attribute to compare against. I need the ability to be able to move a row up or down and have it assigned the next order value.
I've created a new FIDDLE which shows the same table but with 3 new rows that have no data-order value assigned.
If I move any of the sites with no data-order value assigned UP they should get the next data-order value (5) unless they are swapping positions with a row that has a data-order value assigned and then they should get that value and the row they swapped with gets the next value (5).
And the reverse if moving down..
Has anyone got any ideas how I can do this ? Thanks