Archive for February, 2009

Drag & Drop in Table

Wednesday, February 11th, 2009

Javascript needed for this function:

-          jquery-1.2.6.js

-          jquery.tablednd_0_5.js

-          jquery.tablesorter.js

Javascript function needed:

$(function() {

$(”table1″)

.tablesorter({widthFixed: true, widgets: ['zebra']})

});

$(document).ready(function() {

$(”#table1″).tableDnD({

onDrop: function(table, row) {

var rows = table.tBodies[0].rows;

var debugStr = “”;

for (var i=0; i<rows.length; i++) {

debugStr += rows[i].id+” “;

}

document.getElementById(’current_position’).value = debugStr; // To update the field with the new rows position

}

});

});

Note:

“table1” = id of the table that we want to sort

“current_position” = the id of the field where we want to get the updated position of row.

HTML side:

<table>

<thead>

<tr>

<th>Header 1</th>

<th>Header 2</th>

</tr>

</thead>

<tbody>

<tr id = 1><td>column1</td><td>column2</td></tr>

<tr id = 2><td>column1</td><td>column2</td></tr>

</tbody>

</table>

Note:

The <tr> need to have the auto increment id starting from 1.
After all these codes have been inserted correctly, the drag & drop function should be working now. The next thing is how we should update the new position to the database. One of the ways to do it is by having:

-          hidden field that load the id of the items in order. Eg. 2,5,6

-          hidden field of the “current_position” that is mentioned earlier to track the new position. Eg. 3,2,1

In this example,it means that now Item id ‘2’ is in the row 3, item id ‘5’ is in the row 2, and item id ‘6’ is in the row 1. The last step is just updating each row position with the new position from current_position field. Isn’t it easy?? :)

Please refer to this website for more details:  http://www.isocra.com/2007/07/dragging-and-dropping-table-rows-in-javascript/