Table Drag and Drop JQuery plugin
I’ve been using JQuery for a while now and really agree with its tag line that it’s the “The Write Less, Do More, JavaScript Library”. We’ve also got this code for dragging and dropping table rows that has proved very popular, so it seemed natural to combine the two and wrap up the table drag and drop as a JQuery plugin.
Why have another plugin?
Dragging and dropping rows within a table can’t be handled by general purpose drag and drop utilities for a number of reasons, not least because you need to move the whole row, not just the cell that receives the mouse events. Re-parenting the row also requires specific code. Sadly also, effects like fadeIn and fadeOut don’t work well with table rows on all browsers, so we have to go for simpler effects.
What does it do?
This TableDnD plugin allows the user to reorder rows within a table, for example if they represent an ordered list (tasks by priority for example). Individual rows can be marked as non-draggable and/or non-droppable (so other rows can’t be dropped onto them). Rows can have as many cells as necessary and the cells can contain form elements.
How do I use it?
- Download Download jQuery (version 1.2 or above), then the TableDnD plugin (current version 0.5).
- Reference both scripts in your HTML page in the normal way.
- In true jQuery style, the typical way to initialise the tabes is in the
$(document).readyfunction. Use a selector to select your table and then calltableDnD(). You can optionally specify a set of properties (described below).
| 1 | One | some text |
| 2 | Two | some text |
| 3 | Three | some text |
| 4 | Four | some text |
| 5 | Five | some text |
| 6 | Six | some text |
The HTML for the table is very straight forward (no Javascript, pure HTML):
<table id="table-1" cellspacing="0" cellpadding="2">
<tr id="1"><td>1</td><td>One</td><td>some text</td></tr>
<tr id="2"><td>2</td><td>Two</td><td>some text</td></tr>
<tr id="3"><td>3</td><td>Three</td><td>some text</td></tr>
<tr id="4"><td>4</td><td>Four</td><td>some text</td></tr>
<tr id="5"><td>5</td><td>Five</td><td>some text</td></tr>
<tr id="6"><td>6</td><td>Six</td><td>some text</td></tr>
</table>
To add in the “draggability” all we need to do is add a line to the $(document).ready(...) function
as follows:
<script type="text/javascript"> $(document).ready(function() { // Initialise the table $("#table-1").tableDnD(); }); </script>
In the example above we’re not setting any parameters at all so we get the default settings. There are a number
of parameters you can set in order to control the look and feel of the table and also to add custom behaviour
on drag or on drop. The parameters are specified as a map in the usual way and are described below:
- onDragStyle
- This is the style that is assigned to the row during drag. There are limitations to the styles that can be
associated with a row (such as you can’t assign a border—well you can, but it won’t be
displayed). (So instead consider usingonDragClass.) The CSS style to apply is specified as
a map (as used in the jQuerycss(...)function). - onDropStyle
- This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations
to what you can do. Also this replaces the original style, so again consider using onDragClass which
is simply added and then removed on drop. - onDragClass
- This class is added for the duration of the drag and then removed when the row is dropped. It is more
flexible than using onDragStyle since it can be inherited by the row cells and other content. The default
is class istDnD_whileDrag. So to use the default, simply customise this CSS class in your
stylesheet. - onDrop
- Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table
and the row that was dropped. You can work out the new order of the rows by using
table.tBodies[0].rows. - onDragStart
- Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the
table and the row which the user has started to drag. - scrollAmount
- This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the
window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2,
FF3 beta)
This second table has has an onDrop function applied as well as an onDragClass. The javascript to set this up is
as follows:
$(document).ready(function() {
// Initialise the first table (as before)
$("#table-1").tableDnD();
// Make a nice striped effect on the table
$("#table-2 tr:even').addClass('alt')");
// Initialise the second table specifying a dragClass and an onDrop function that will display an alert
$("#table-2").tableDnD({
onDragClass: "myDragClass",
onDrop: function(table, row) {
var rows = table.tBodies[0].rows;
var debugStr = "Row dropped was "+row.id+". New order: ";
for (var i=0; i<rows.length; i++) {
debugStr += rows[i].id+" ";
}
$(#debugArea).html(debugStr);
},
onDragStart: function(table, row) {
$(#debugArea).html("Started dragging row "+row.id);
}
});
});
| 1 | One | |
| 2 | Two | |
| 3 | Three | |
| 4 | Four | |
| 5 | Five | |
| 6 | Six | |
| 7 | Seven | |
| 8 | Eight | |
| 9 | Nine | |
| 10 | Ten | |
| 11 | Eleven | |
| 12 | Twelve | |
| 13 | Thirteen | |
| 14 | Fourteen |
What to do afterwards?
Generally once the user has dropped a row, you need to inform the server of the new order. To do this, we’ve
added a method called serialise(). It takes no parameters but knows the current table from the
context. The method returns a string of the form tableId[]=rowId1&tableId[]=rowId2&tableId[]=rowId3...
You can then use this as part of an Ajax load.
This third table demonstrates calling the serialise function inside onDrop (as shown below). It also
demonstrates the “nodrop” class on row 3 and “nodrag” class on row 5, so you can’t pick up row 5 and
you can’t drop any row on row 3 (but you can drag it).
$('#table-3').tableDnD({
onDrop: function(table, row) {
alert($.tableDnD.serialize());
}
});
Ajax result
Drag and drop in this table to test out serialise and using JQuery.load()
| 1 | One | |
| 2 | Two | |
| 3 | Three (Can’t drop on this row) | |
| 4 | Four | |
| 5 | Five (Can’t drag this row) | |
| 6 | Six |
This table has multiple TBODYs. The functionality isn’t quite working properly. You can only drag the rows inside their
own TBODY, you can’t drag them outside it. Now this might or might not be what you want, but unfortunately if you then drop a row outside its TBODY you get a Javascript error because inserting after a sibling doesn’t work. This will be fixed in the next version. The header rows all have the classes “nodrop” and “nodrag” so that they can’t be dragged or dropped on.
| H1 | H2 | H3 |
|---|---|---|
| 4.1 | One | |
| 4.2 | Two | |
| 4.3 | Three | |
| 4.4 | Four | |
| 4.5 | Five | |
| 4.6 | Six | |
| H1 | H2 | H3 |
| 5.1 | One | |
| 5.2 | Two | |
| 5.3 | Three | |
| 5.4 | Four | |
| 5.5 | Five | |
| 5.6 | Six | |
| H1 | H2 | H3 |
| 6.1 | One | |
| 6.2 | Two | |
| 6.3 | Three | |
| 6.4 | Four | |
| 6.5 | Five | |
| 6.6 | Six |
The following table demonstrates the use of the default regular expression. The rows have IDs of the
form table5-row-1, table5-row-2, etc., but the regular expression is /[^\-]*$/ (this is the same
as used in the NestedSortable plugin for consistency).
This removes everything before and including the last hyphen, so the serialised string just has 1, 2, 3 etc.
You can replace the regular expression by setting the serializeRegexp option, you can also just set it
to null to stop this behaviour.
$('#table-5').tableDnD({
onDrop: function(table, row) {
alert($('#table-5').tableDnDSerialize());
},
dragHandle: "dragHandle"
});
| 1 | One | some text | |
| 2 | Two | some text | |
| 3 | Three | some text | |
| 4 | Four | some text | |
| 5 | Five | some text | |
| 6 | Six | some text |
In fact you will notice that I have also set the dragHandle on this table. This has two effects: firstly only
the cell with the drag handle class is draggable and secondly it doesn’t automatically add the cursor: move
style to the row (or the drag handle cell), so you are responsible for setting up the style as you see fit.
Here I’ve actually added an extra effect which adds a background image to the first cell in the row whenever
you enter it using the jQuery hover function as follows:
$("#table-5 tr").hover(function() {
$(this.cells[0]).addClass('showDragHandle');
}, function() {
$(this.cells[0]).removeClass('showDragHandle');
});
This provides a better visualisation of what you can do to the row and where you need to go to drag it (I hope).
Version History
| 0.2 | 2008-02-20 | First public release |
| 0.3 | 2008-02-27 | Added onDragStart option Made the scroll amount configurable (default is 5 as before) |
| 0.4 | 2008-03-28 | Fixed the scrollAmount so that if you set this to zero then it switches off this functionality Fixed the auto-scrolling in IE6 thanks to Phil Changed the NoDrop attribute to the class “nodrop” (so any row with this class won’t allow dropping) Changed the NoDrag attribute to the class “nodrag” (so any row with this class can’t be dragged) Added support for multiple TBODYs–though it’s still not perfect Added onAllowDrop to allow the developer to customise this behaviour Added a serialize() method to return the order of the rows in a form suitable for POSTing back to the server |
| 0.5 | 2008-07-11 | Now supports having a column as a drag handle (specify a class for the dragHandle option when configuring).
Improved the serialize method to use a default (but also settable in the options) regular expression for generating the serialized string. The default is /[^\-]*$/ which will remove everything before a final hyphen, so item-s1 becomes s1. Added $(‘…’).tableDnDUpdate() to cause the table to update its rows so the drag and drop functionality works if, for example, you’ve added a row. Added $(‘…’).tableDnDSerialize() which allows you to serialize a table from any javascript code. Removed remaining $ and replaced with jQuery so that it should work with Prototype and Scriptaculous |
Tags: Drag & Drop, Javascript, Web
Subscribe to news from Isocra



February 24th, 2008 at 5:34 pm
Thank you kindly, this is working nicely for me!
I have a table that I am refreshing (as in, totally wiping the HTML and replacing it) every few seconds from a server using AJAX, and after every refresh I am calling the $(“#table-1″).tableDnD() method over and over. First off, is the best way to handle things? Or is there a way to trigger the function once when the page first loads, and not have to keep calling it?
Another thing that happens for me in this case is: you start dragging a row, then it snaps back to its original position after the table gets refreshed (the server hasn’t picked up on the change in position yet because the onDrop() method hasn’t been called yet)… luckily though it will still put it in its correct place once you release the mouse. I want to figure out a way to disable my refresh from replacing the HTML once a drag has begun — it seems that I could apply the onDragClass method and then check the DOM for that in the refresh method, but is that the best way to handle this idea?
By the way I noticed that this plugin was scrolling the page for me in Firefox if I had a table that was running off the page; great work!
February 24th, 2008 at 5:42 pm
Just wanted to say, in my case I need to know the id of of the row that the drag & dropped row was dropped onto, here is how I handled that:
onDrop: function(table, row) { var rows = table.tBodies[0].rows; var droppedon = ""; if (rows.length < 2) return false; if (rows[0].id == row.id) // dragged to the top, replaced the first one droppedon = rows[1].id; else if (rows[rows.length-1].id == row.id) // dragged to the bottom, replaced the last one droppedon = rows[rows.length-2].id; else // search for where it was dropped on for (var i=0; i0 && rows[i-1].id == row.id) droppedon = rows[i].id; if (droppedon!="") return true; // so something return false; }February 24th, 2008 at 5:44 pm
Hmm, that else statement should state:
else // search for where it was dropped on for (var i=0; i0 && rows[i-1].id == row.id) droppedon = rows[i].id;Okay, sorry for so many comments, I just really like your plugin!
February 24th, 2008 at 5:46 pm
Hmm, that else statement should state: (I’ll try again!)
Okay, sorry for so many comments, I just really like your plugin!
February 24th, 2008 at 5:47 pm
Agh, something is up with your comments, here is what I am trying to put right after the for() statement:
i f ( i > 0 & & r o w s [ i - 1 ] . i d = = r o w . i d )
February 24th, 2008 at 6:19 pm
Okay, let me try that one more time, here is my full function:
var rowsBeforeDragAndDrop;
// called upon every refresh
function InitiateDragAndDrop() {
rowsBeforeDragAndDrop = $(‘#queueContent’).children();
$(“#queueTable”).tableDnD({
//onDragClass: “myDragClass”,
onDrop: function(table, row) {
var rows = table.tBodies[0].rows;
var droppedon = “”;
if (rows.length 2 ) {
for ( var i=1; i < rows.length-1; i++ ) {
if ( rows[i].id == row.id && rows[i-1].id == rowsBeforeDragAndDrop[i].id )
droppedon = rows[i-1].id;
else if ( rows[i].id == row.id && rows[i+1].id == rowsBeforeDragAndDrop[i].id )
droppedon = rows[i+1].id;
}
}
if (droppedon!=”")
return ChangeOrder(“switch?uid1=”+row.id+”&uid2=”+droppedon);
return false;
}
});
}
February 24th, 2008 at 6:24 pm
I give up, here is my function — I think it’s right:
http://pastebin.com/d3ccbe0ad
It behaves pretty well with my “refresh” and multiple sorts.
Again, thank you and I apologize for posting so many freakin comments!
February 24th, 2008 at 6:41 pm
I can see the extra style being applied from the CSS class, but I can’t see it through the DOM:
onDragClass: “myDragClass”,
Maybe something is up with my implementation….
February 24th, 2008 at 6:42 pm
Meant to add, alert($(“#queueTable”).attr(‘class’)); never reports the “myDragClass” mid-drag.
February 27th, 2008 at 12:05 pm
Hi Nathan,
If you refresh the table (that is, replace all the HTML) then yes, you do have to call TableDnD() again. There shouldn’t be any memory leakages as far as I know, but it might be an issue. I haven’t built any systems where I need to refresh the table constantly.
To solve the refresh-in-the-middle-of-dragging problem, there’s now a new config option in version 0.3. You can specify an onDragStart function that will be called when the user first presses the mouse down. You could use this to disable refreshing until the drag is finished?
February 27th, 2008 at 10:08 pm
[...] using the jQuery sortables plugin. I was asked how this could be done with table rows. The jQuery TableDnD plugin comes to the [...]
February 28th, 2008 at 9:30 am
Hi aliaspooryorik, thanks for the link to your article and how to serialise the results. I ought to add a serialise method really, I’ll do that in the next release
February 28th, 2008 at 2:26 pm
Will this have row ghosting and serializing soon? Like the Sortables, anything being dragged should be ghosted… if you know what I mean.
February 28th, 2008 at 2:47 pm
It will have serialization soon(ish) when we have time, but ghosting is more difficult. Table rows are not like DIVs and SPANs and can’t be moved in quite the same way–which is why there’s a separate plug-in for doing the table row sorting.
February 29th, 2008 at 6:17 am
[...] Table Drag and Drop JQuery plugin | Isocra (tags: jquery) [...]
March 3rd, 2008 at 7:02 am
How would I go about adding support for sub-levels?
Example:
Main 1 Main 2 Main 3 Sub 1 Sub 2 Sub 3 Main 4 Sub 1And have the ability to move the sub-elements to other sub-elements or main-elements.
March 3rd, 2008 at 11:11 am
[...] TableDnD é uma extensão para jQuery que permite criares o efeito de drag e drop em cada fila da tua tabela.Dá jeito para quando queres ter uma lista de tarefas, e queres deixar os teus users poderem reorganizar a lista. Partilhar esta Entrada (Ninguem Votou) Loading … [...]
March 3rd, 2008 at 4:17 pm
[...] Table Drag and Drop JQuery plugin | Isocra AJAX Scripts Add comments Table Drag and Drop JQuery plugin | Isocra. [...]
March 5th, 2008 at 4:00 pm
It’s very powerful thing, thanks a lot!
March 10th, 2008 at 12:06 pm
Why don’t you make the nodrag/nodrop classes instead of attributes that prevent the markup from being valid ?
March 10th, 2008 at 1:15 pm
That would be nice to be able to determinate if the row hasn’t moved.
For instance, I’m actually adding a “dropped” class to the moved elements with onDrop function, but this gets applied even if the row didn’t really change position in the table.
Nice work anyhow.
March 10th, 2008 at 3:03 pm
I’ve been tweeking a bit the script to have the nodrag/nodrop via classes, it goes like this :
// John Tarr added to ignore rows that I've added the NoDnD attribute to (Header rows) var nodrop = $(row).hasClass("nodrop"); if (nodrop == false) { //There is no NoDnD attribute on rows I want to drag // John Tarr: added to ignore rows that I've added the NoDnD attribute to (Category and Header rows) var nodrag = $(rows[i]).hasClass("nodrag"); if (nodrag == false) { //There is no NoDnD attribute on rows I want to dragFeel free to implement this in the next version if you like valid html
March 10th, 2008 at 3:18 pm
Hi Famic,
Thanks for that. I’m actually working on a new version that has a callback method so that yo can decide whether to allow drop or not–that way you can use classes or any logic you like. Including support for sub-levels as requested by ShaunS.
I agree that using classes is cleaner than non-standard html attributes though, so thanks for the input.
March 10th, 2008 at 3:54 pm
One other cool feature would be to mix this with some multiselection plugins and be able to grab several rows and move them at once… Dunno if how hard that could be, though. Just throwing in ideas
March 10th, 2008 at 7:04 pm
Also that would be quite useful to be able to trigger the drag’n'drop only from a specific … To prevent inplace editors to conflit with this drag’n'drop option
March 10th, 2008 at 7:19 pm
I meant a specific “td” but I put the bracets around it :/
March 10th, 2008 at 9:52 pm
I’ve tweaked the script again to have a “dragger” td and let the other td’s inactive…
// John Tarr: added to ignore rows that I've added the NoDnD attribute to (Category and Header rows) var nodrag = $(rows[i]).hasClass("nodrag"); if (nodrag == false) { //There is no NoDnD attribute on rows I want to drag jQuery(".dragger").css("cursor", "move"); jQuery(rows[i]).mousedown(function(ev) { if (jQuery(ev.target).hasClass("dragger")) { jQuery.tableDnD.dragObject = this; jQuery.tableDnD.currentTable = table; jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev); if (config.onDragStart) { // Call the onDrop method if there is one config.onDragStart(table, this); } return false; } }) // Store the tableDnD objectIt might not be the best way to do it, but it works fine…
March 13th, 2008 at 10:12 am
nice work!
currently, I am building a web-based information system which need one feature like this, but it requires drag and drop on tbody tags rather than on tr tags.
here is one sample html
Dragging and dropping Tbody within a table
Tbody 1 Title
this is title
Tbody 1 Title
this is title
Tbody 2 Title
this is title
Tbody 2 Title
this is title
Tbody 3 Title
this is title
Tbody 3 Title
this is title
I need to be able to drag the whole tbody and move upward or downward, just like doing on the rows.
how can I do it?
thanks in advaned
March 13th, 2008 at 10:15 am
oops, the html of table got striped. let me clarify here, there is a table has one thead tag, serveral tbody tags in it.
March 13th, 2008 at 10:33 am
Hi Logan, that’s pretty difficult! At the moment the code is all about taking one particular row and moving it within the table, to move whole TBODYs you’d need to change the code to work at the TBODY level instead. You might find it easier to start with the raw (non-jquery) code which you can then adapt as you need.
I’m working on integrating what Famic has posted and adding a callback method. I was also going to look into the impact of having multiple TBODYs, but I’m afraid that I’m planning to add TBODY dragging or multi-selection just yet.
March 14th, 2008 at 9:30 pm
Hi, Nathan…
Good job on the plug-in.
I would like to use it, but when I grab a row to move it, the browser window begins to scroll up and doesn’t stop.
Any ideas about this problem?
I’m using IE7.
Thanks,
Rick
March 14th, 2008 at 9:53 pm
Oops, wrong author reference.
Should have been, “Hi, DenisH” ! Sorry
Rick
March 16th, 2008 at 12:06 am
Well done! I spent the better part of a frustrating day trying to get row dragging to work with jQuery UI a few months ago and finally gave up.
I did catch a bug; radio boxes reset to defaults when their containing row is dragged. This only happens in IE, not Firefox or Safari. I reported it as a bug in the issue queue at plugins.jquery.com, as well.
March 17th, 2008 at 5:09 pm
Just in case anyone is confused as to why something like
.myDragClass {
background: #ffc;
}
isn’t working, you’ll need:
.myDragClass td {
background: #ffc;
}
March 17th, 2008 at 11:39 pm
Is anyone create some php id script update? I was trying to link eveything but unsuccessful…
March 20th, 2008 at 2:09 am
Just to say : thanks
.
March 20th, 2008 at 8:50 am
Hi! Thnx 4 script.
It would be great to know (a flag 0/1 or something like it) after drop, row order was changed or not (i.e. when row position ondragstart = row position ondrop).
March 21st, 2008 at 7:46 pm
Thank you for this!
Any progress on implementing the serialization? I would like to pass the new results into cf, like:
http://aliaspooryorik.wordpress.com/2008/02/21/sortable-list-with-jquery-and-coldfusion/
but without serialization im not sure how to go about doing it. Any suggestions would be great.
March 21st, 2008 at 9:20 pm
nevermind they had the info on the site i previously posted
I am interested in the ghosting though, has anyone made any progress?
March 22nd, 2008 at 1:29 am
Whoop, sorry didn’t think you’d publish all my random thoughts!
Just wanted to put in a feature request, it would be cool if you could do some sort of like sortable groupings.
How would I go about adding support for sub-levels?
Main 1
Main 2
Main 3
Sub 1
Sub 2
Sub 3
Main 4
Sub 1
And have the ability to move the sub-elements to other sub-elements or main-elements.
This would be extremely nice; personally, I would want to sometimes disable sub-elements from jumping to other main-elements, but still sortable within their original main-element.
March 26th, 2008 at 10:26 am
Hi folks, sorry for the lack of progress, we’ve been busy on other things. A new version is just being tested which will include the ability to register methods that get called to determine whether rows can be dragged and whether they can be dropped on other rows.
We’re also planning on implementing a serialize method. Currently the plan is to work in the same way as the Sortables plugin, so serialize() will return “table1[]=rowId1&table1[]=rowId4&table1[]=rowId2&table1[]=rowId3″ (assuming the table ID is table1 and row 4 has been dragged to be after row 1). Is that what people want? If not, then let us know how you’d like it to be.
March 27th, 2008 at 3:03 am
Sounds great DenisH, the thing I like about this plugin so much is just how simplistic its usage is, so easy to add into what I already have.
March 27th, 2008 at 8:44 pm
Is there a way to disable certain rows (tr) from being moved?
March 28th, 2008 at 10:38 am
Yes, if you add an attribute called “NoDrag” to the row, so you have
March 28th, 2008 at 2:05 pm
DenisH, thank you so much for this plugin! It works great.
I do have a question, though: The code seems to be checking for the first tbody in each affected table. In the project that we are working on we have tables with multiple tbodies, each with a header row and some content rows. When I apply tableDnD() to one of these tables, only the first tbody becomes sortable. – We need to sort the rows within all tbodies. (We don’t even want to drag rows across the different tbodies, only within each tbody)
Do you have a suggestion for how we can achieve this with your plugin?
March 28th, 2008 at 3:20 pm
Yup, that’s a bug. We ought to check all the TBODYs but at the moment it only checks the first one. If you have a look through the source code for tbodies[0].rows and add in an extra loop to go round all the tbodies, then that should work. We will aim to fix this in a new release shortly.
March 28th, 2008 at 6:02 pm
Thanks for the script, very useful!
I am running into an issue though. When I used this script on a html page with the table full rendered, works great, but when I use this script on a table generated via JS the DnD magic doesn’t get bound to table.
$(document).ready(function(){
buildMyTable(“table-1″);
$(“#table-1″).tableDnD();
});
I suspect it has to do with the sequence of events, thanks again.
March 28th, 2008 at 6:42 pm
Hi Kai,
I think you’re right. It will be to do with the sequence of events. if buildMyTable is using any sort of Ajax or anything asynchronous to build the table then it won’t all be there by the time that you call tableDnD(). But you should be able to call it inside buildMyTable as the last line or so.
Have you tried using FireBug and putting some breakpoints to see what’s going on?
March 28th, 2008 at 7:23 pm
Hi DenisH,
Yes, buildMyTable makes an async call to jQuery’s .load() method:
$(“#table-1″).load(“/lib/whohasmydata.cfm”);
I actually tried:
$(“#table-1″).load(“/lib/whohasmydata.cfm”);
$(”#table-1″).tableDnD();
Then:
$(“#table-1″).load(“/lib/whohasmydata.cfm”).tableDnd();
Still no luck. Ahh i c, I had no idea FireBug let you debug JS, that’s great, thanks!
Well, at least I know I’m going down the right path. Thanks agains.
March 28th, 2008 at 7:30 pm
Hi Kai, right so the problem you’ve got is that the load is asynchronous, but returns immediately. What you need to do is change this to:
// Load takes 3 parameters: url, data, callback. The callback is called when the url has been loaded $("#table-1").load("/lib/whohasmydata.cfm”, null, function() { // this is called when the load is complete $("#table-1").tableDnd(); // I think it should work if you do $(this).tableDnD(), but I haven't tested it });March 28th, 2008 at 8:14 pm
Perfect! That’s what I was missing, wicked awesome
Thanks again for your help…
April 2nd, 2008 at 12:40 pm
A little fix for IE6.
Dragging a TR makes the page always “scroll down”. With this fix you can scroll up and down.
Change Line 135:
if (document.all) { // Windows version yOffset=document.body.scrollTop; }To:
if (document.all) { // Windows version //yOffset=document.body.scrollTop; if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') { yOffset = document.documentElement.scrollTop; } else if (typeof document.body != 'undefined') { yOffset=document.body.scrollTop; } }April 2nd, 2008 at 7:43 pm
Is background-color one of the properties that cannot be set?
We’d like to have a unique color for the row being dragged, have tried onDragStyle, onDragClass, and onDropStyle to no effect.
Great tool!
Thank you
April 3rd, 2008 at 8:55 am
Hi Centralb, you can set the class or the style of the row being dragged. If you look at table-2 above you’ll see that we’ve set the onDragClass to be myDragClass. This is defined as follows:
tr.myDragClass td { color: yellow; background-color: black; }So this says that any TD inside a row that is of class myDragClass should be displayed as shown.
Hope this helps
April 3rd, 2008 at 4:16 pm
Wow, thanks man! You saved my life with this. I had huge problems in my CMS with interface + nested sortables. It was clunky, didn’t work at all in IE7 with TinyMCE loaded at the same time and in FF it required the equivalent of a flight certificate to maneuver correctly.
Yours just work and I have it working nested even! (Of course you can’t drag table rows from one table to another, but I have another mechanism for that, so this is exactly what I want).
Somehow playing around with ul and li list-items always brings disappointment to my life, whereas tables are the way to go if you want it hasslefree. So thanks!
April 5th, 2008 at 6:17 pm
Hi folks, finally we’ve got version 0_4 out of the door. It incorporates many of the suggestions and fixes suggested in the comments above. So thanks to all and keep those comments coming!
April 9th, 2008 at 12:11 am
Thanks Denis, I enjoy experimenting with all these new features!
April 10th, 2008 at 4:02 pm
Hi, your plug-in is really brilliant !! I love it!
Thank you much for your effort.
April 14th, 2008 at 5:26 pm
good job.
just i needed!
April 16th, 2008 at 8:44 pm
Perfect! Just what I am looking for. Could you possibly provide a sample bit of code where you click a ’submit’ button after sorting to submit a serialized list of the sorted table to a php script? I see how you do it with ajax on each drop, but that would be more calls than I need to the database. (Sorry if what I am asking for is obvious – I am a jQuery n00b!)
April 23rd, 2008 at 4:18 am
Denis nice work on this plugin!
@Sara – you could populate just one hidden field with the jquery serialised list after every drop and then access that field after posting the form. Alternatively (and i find this easier to work with), if you only need to know the new arrangement of id’s you could try adding the unique id to each row via a hidden form field, for example:
First Row Content
Second Row Content
Where each value is the database id. After you submit the form, the rearranged id’s in their new order should be available as an array $_POST['row_id']; Hope that made sense…
April 28th, 2008 at 7:07 pm
This is really great plugin. I have been able to get some php behind it and update list order for a form generator. Now I just need to figure out how to do the following:
after I add a new element to table-1 I am able to delete and sort rows. I want to be able to call serialize without starting the drag and drop. ie. add form field (6) delete form field (2). submit form -fire serialize function.
I just can’t figure out how to access the serialize function even if the tr elements did not change position (were not dragged)
any suggestions??
great work on this plugin
April 28th, 2008 at 9:30 pm
Hi Andy and Sara,
I must admit I hadn’t anticipated people wanting to call serialize from outside the onDrop, but I think you can achieve the same thing with the following lines:
jQuery.tableDnD.currentTable = document.getElementById("table-3"); // use your table ID obviously alert(jQuery.tableDnD.serialize());Basically all you need to do is ensure that currentTable is initialized to the right document element and then serialize() works as required.
In the next version I’ll wrap this up more neatly.
May 2nd, 2008 at 11:16 am
This is great. Simple, light-weight, easy to implement. Thank you!
May 3rd, 2008 at 8:25 pm
Nice work. I wanted to define a specific class as a dragHandle, so I made the following changes:
build: function(options) { // Make sure options exists options = options || {}; // Set up the defaults if any this.each(function() { // Remember the options this.tableDnDConfig = { dragHandle: options.dragHandle ? options.dragHandle : "td", ///// added this onDragStyle: options.onDragStyle, onDropStyle: options.onDropStyle, ... makeDraggable: function(table) { // Now initialise the rows var rows = table.rows; //getElementsByTagName("tr") var config = table.tableDnDConfig; for (var i=0; i<rows.length; i++) { // To make non-draggable rows, add the nodrag class (eg for Category and Header rows) // inspired by John Tarr and Famic var nodrag = $(rows[i]).hasClass("nodrag"); if (! nodrag) { //There is no NoDnD attribute on rows I want to drag jQuery(rows[i]).mousedown(function(ev) { if (jQuery(ev.target).is(config.dragHandle)) { ///// changed this jQuery.tableDnD.dragObject = this; jQuery.tableDnD.currentTable = table; ...That way the existing functionality will be the same, unless you specify a dragHandle selector.
May 3rd, 2008 at 8:30 pm
Oh – I also removed the .style(“cursor”, “move”) wherever that was. I think when I used {dragHandle: “.drag”} the whole row still had the move cursor, and I’d rather do that in my stylesheet anyway.
May 5th, 2008 at 8:05 am
I have added a enable/disable function to this drag and drop, i would like if you could impliment one for future releases, i will post mine but it might not be the best way of doing it. I have also taken out the .css(“cursor”, “move”) aswell and added in my own css class to make it easier to remove on disable and to make the code look prettier. (I don’t like inline css)
Here is the link to the code, the highlighted bits are the changes.
http://pastebin.com/f4e702774
May 7th, 2008 at 7:31 am
Hi there,
This is truely awesome work! I’m quite new ot this, but is it possible to handle this as a questionnaire and have the results ’sorting’ send to a db for evaluation?
Thanks in advance!
May 7th, 2008 at 11:51 am
in reply to DenisH’s post April 28th, 2008 at 9:30 pm
If a row is being dragged at the moment on another table, the currentTable variable will be overwritten and we get problems. In that case, here’s an external javascript function for serialization, which of course may be changed for other serialization formats
function serializeTableOrdering(table) { if (table) { var result = ""; var tableId = table.id; var rows = table.rows; for (var i=0; i 0) result += "&"; result += tableId + '[]=' + rows[i].id; } return result; } return ""; }cheers
May 12th, 2008 at 6:17 pm
Hi there,
Thanks for this great plugin. It’s the closest I’ve found to what I needed for a project. However, my table has several dynamic options, where some cells have checkboxes and other cells are clickable. Basically, what I needed was a way to tell tableDnD to ignore certain cells when rearranging. Luckily I was able to get this working easily by changing one line in your plugin. So I thought I’d share it here for others to enjoy >.<:
Line 111, in makeDraggable
if (ev.target.tagName == “TD” && !$(ev.target).hasClass(“nodrag”)) {
It basically just checks for an additional class flag in the cell.
Tested in FF2 and IE6.
Thanks again!
May 15th, 2008 at 8:37 am
Thanks man, I’ve been looking for something like this since Noah built his boat. Yours is the only stable one out there, works A1 in FF and IE7.
Very cool, very easy to install, very nice. Thanks!
May 18th, 2008 at 7:25 pm
Awesome work. How about a drag drop for columns?
May 20th, 2008 at 10:15 am
Hi there, I just wanted to say you’ve done a great job with this plugins!
I’ve got a little suggestion though. Would it be possible improving the serialize() function a bit so I could also see in which tbody certain rows are?
May 21st, 2008 at 11:50 am
Hello,
I’ve did a little modification in serialize(). It now supports an optional parameter name that’s used for the name as url query.
Usefull when you have several table’s on one page that are processed by the same ajax script.
serialize: function(name) { if (jQuery.tableDnD.currentTable) { var result = ""; var rows = jQuery.tableDnD.currentTable.rows; name = (name) ? name : jQuery.tableDnD.currentTable.id; for (var i=0; i 0) result += "&"; result += name + '[]=' + rows[i].id; } return result; } else { return "Error: No Table id set, you need to set an id on your table and every row"; } }example:
onDrop: function(table, row) { $('#surface_profiles_order_result').load("ajax.php?action=order&type=some_type&" + $.tableDnD.serialize('id')); }May 23rd, 2008 at 8:50 pm
You want to replace $ by jQuery in lines 108 and 261.
May 26th, 2008 at 11:09 am
Hi all, thanks for all the feedback. I’m working on the next version which will include many of the enhancements including regexp in the serialize method, another serialize method that you can call on any table so $(‘….’).tableDnDSerialize(), also better handling of multiple tbodies and possibly dragging between tables.
Unfortunately I don’t intend to handle dragging columns (because columns aren’t draggable things in HTML, it would potentially be possible to make column header cells draggable and then move the rest of the column cells on drop, but that sounds like quite a bit of work). I’m afraid that I can’t really generate server-side code examples for all possible cases either. That’s rather up to you.
May 30th, 2008 at 10:27 pm
I have a question. I am needing this to run on a page that is also running prototype and scriptaculous. I had to use a jQuery.noConflict(); to allow my jQuery to work when using the edit in place. I tested this with your tableDnD and it broke it. Any ideas?
June 2nd, 2008 at 1:10 pm
hi,
i have a problem.
i did some changes on onDrop code
$(document).ready(function() { $('#table-3').tableDnD({ onDrop: function(table, row) { document.write(""); } }); });like this. but it does not work. where is my fail.
sorry my english
thank you for all
June 2nd, 2008 at 1:14 pm
into the document.write is
document.write();
June 2nd, 2008 at 1:15 pm
sorry into the document.write is not seen.
in it there is input hidden tag. value is serialize
June 2nd, 2008 at 1:20 pm
Hi erkunt,
document.write() only works when you’re initially generating the document. It won’t work when the document is already generated. If you want to replace some HTML, then use $(“…..”).html(“<input type=’hidden’ name=’hiddenInput’ value=’something’/>”) but you have to specify where you want it to in the “…..” bit. Look at the jquery documentation for examples.
June 2nd, 2008 at 1:24 pm
Hi Jacob, sorry for not getting back to you earlier.
In the current public version, there are two places where I’ve forgotten to replace $ with jQuery (lines 108 and 261). This was kindly pointed out a week ago or so by Foppe Hemminga. If you change these, it should work. If not, let me know and exactly what error message you get (or symptom or whatever) and I’ll try and fix it in the next version which is almost ready for release.
June 5th, 2008 at 10:17 am
OK, this work great until i add the part:
// Initialise the second table specifying a dragClass and an onDrop function that will display an alert $("#GridView1").tableDnD({ onDragClass: "myDragClass", onDrop: function(table, row) { var rows = table.tBodies[0].rows; var debugStr = "Row dropped was "+row.id+". New order: "; for (var i=0; i<rows.length; i++) { debugStr += rows[i].id+" "; } $(#debugArea).html(debugStr); }, onDragStart: function(table, row) { $(#debugArea).html("Started dragging row "+row.id); } });I also added:
tr.myDragClass td { background-color: #336699; } in my style sheet.
But all functionality is simply gone dead. Any ideas what I’m missing. I’ve been throug the whole long discussion but can’t seem to find the bugger. !?
June 5th, 2008 at 10:17 am
I also did add the debugArea …
June 5th, 2008 at 10:52 am
OK, located it to being problems with ‘invalid character’ at these lines:
$(#debugArea).html(debugStr);
and
$(#debugArea).html(“Started dragging row “+row.id);
I’m using IE 7 Windows XP. Implemented the code in ASP.NET. But it works fine until I add that part of the script. So somehow it doesn’t like some character in those lines. I suspect it to be either the $ or the #.
Any clues, anyone?
June 5th, 2008 at 11:05 am
My bummer!
Had to add in the GridView1_RowCreated event handler:
if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("id", e.Row.RowIndex.ToString()); }June 5th, 2008 at 11:06 am
AND remove the # character in the $(#debugArea).html(“string”) lines;
June 9th, 2008 at 8:12 pm
Hey DenisH. I love this addon. I was working on creating my own for a few days, but keeping track of cursor location was getting to troublesome. Unfortunately, the rows I am working with do not contain text, they contain links to other pages, which in turn contains the text. I am unable to drag the linked text inside my rows and was wondering if there was a work around for this situation. Again, thanks for the help and keep up the good work!
June 10th, 2008 at 7:39 am
Hi Lucas, in order not to interfere with links and form fields, the code deliberately doesn’t let you drag anything other than the table cells. I’m guessing that your table only contains cells with links in which is why you can’t drag the rows. So the trick I think is to add an extra drag “handle” cell at the beginning or end of each row. You could even put an image in the cell to indicate that that’s where the user should drag from. This cell, because it doesn’t have any links in should allow the row to be dragged.
I’m working on a new version which will specifically supports drag handles, but I’m afraid it’s not quite completed yet.
If this doesn’t work, or I’ve guessed wrong. Post back with some example rows
June 10th, 2008 at 6:02 pm
I may have to take your suggestion and create a dragging “handle” beside each row. Another thing that I noticed was occurring is, for my table to be draggable with your addon it must consist of tags. I am working with the Django framework and the administrative tables it creates all use tags instead. I am not sure if this is something you could implement, but it is something to consider.
June 10th, 2008 at 6:26 pm
I have tried adding a drag icon, but it will not allow me to drag the row by clicking on the icon. I have also tried adding the words “Drag” next to the icon, and it will let me drag that text, which is a good thing. Unfortunately, I do not like the color black in this table, so i wrapped the text in a font tag to change its color. By adding this font color, I am no longer able to drag the row by clicking on the word “Drag”. Do you have any suggestions on how to remedy this situation?
June 10th, 2008 at 6:52 pm
Also, your serialize command does not work for me because my table rows are created generic, with no row id on them. Would it be possible to implement a different way to serialize the tables without depending on them having their own unique identifiers?
June 11th, 2008 at 5:53 am
Hi Lucas, for the drag icons, the way to do it is to use CSS. Definitely don’t use a FONT tag, that is deprecated in HTML 4 and XHTML. Instead, add a class to the cell, for example
<td class="dragHandle"> </td>. This creates a cell with a non-breaking space in it (so that the border is all drawn correctly but there’s no visible text.Now in the stylesheet or style section of the header you can add a background image. Something like:
td.dragHandle { background-image: url(images/drag.gif); background-repeat: no-repeat; background-position: center center; }This adds a single centered background image. You can also set the width if you need to here.
As for serializing rows without IDs, I’m afraid you’ll have to write your own code to do this. Iterating over the rows in a table is not difficult either in Javascript or using jQuery. Then you can grab whichever bits of information from your rows that you need.
June 11th, 2008 at 1:40 pm
[...] Vielleicht hilft das ja: Table Drag and Drop JQuery plugin | Isocra [...]
June 12th, 2008 at 10:58 am
I have requirement , there i need to drag a keyword from on div tag.. and i need to drop in editor. Is it possible , if possible can any one tell me how can i do it?
June 12th, 2008 at 5:56 pm
I set this up alongside the “Live Query” plugin: http://brandonaaron.net/docs/livequery/
Result: works great!
What I have is an AJAX table which is being refreshed every X seconds — with this LiveQuery I can just totally replace the table’s HTML, without having to re-initialize this tableDnD plugin every time.
This plugin been working great ever since the first release, so I wanted to say thanks again.
I am very eager for maybe having a way of setting special rules for hierarchical sorting.
(so you can specify which rows can be dragged where, more precisely than what you added for v0.4)
June 14th, 2008 at 3:35 am
Could I make another request? How would I go about setting up a table where I could select multiple rows, and then drag/drop the entire selected group at once? Is there any way to get a box I can kind of draw with my mouse cursor that will select multiple rows for this purpose? I am thinking in the same fashion that the Windows Explorer works for selecting files in a folder, that would help for huge lists that need a lot of custom sorting very quickly.
June 17th, 2008 at 9:49 am
@DenisH Man I wish I would’ve known about your plugin before. I needed something like this for a project!
I’ll be announcing it to the jQuery mailing list and Twitter acct. I hope you keep enhancing it. This a feature that’s constantly being requested and I would suggest you contact jQuery UI team lead Paul Bakaus to chat about this. He and I were discussing this very same functionality for a future release of jQuery UI. Reach me via email if you’d like an intro.
Rey – jQuery Team
June 18th, 2008 at 8:21 am
Hi,
This is really a great tool…
June 18th, 2008 at 8:25 am
Hi,
I was able to run the plugin using a simple html file only.
I tried to incorporate it to a joomla 1.5 page and it was
not running.
This is the error from firebug:
$(“#left_d”).tableDnD is not a function
(no name)()index.php (line 24)
ready()jquery-1.2.6.min…. (line 27)
ready()jquery-1.2.6.min…. (line 27)
nodeName([function()], function(), undefined)jquery-1.2.6.min…. (line 21)
ready()jquery-1.2.6.min…. (line 27)
[Break on this error]$(“#left_d”).tableDnD();
and this is my code:
$(document).ready(function(){
alert(“document is ready”);//this is working
$(“#left_d”).tableDnD();
alert($.tableDnD.serialize());
});
June 18th, 2008 at 9:24 am
Hi Bryan, if it says that tableDnD is not a function then that suggests that the jquery.tablednd.js file is not being read in properly (you can check this easily in FireBug by going to the script tab and then in the pull-down menu next to “Inspect” you should see jquery.tablednd.js. If it’s not there, that’s your problem.
Alternatively if it is there, then it might be due to a clash with other Javascript libraries that redefine the $ (e.g. Prototype or Scriptaculous). There is a known bug in the current release where $ is used directly. Have a look at this comment by Foppe above. You would also need to call
jQuery.noConflict();so that it doesn’t clash. Having said that since in your code the document.ready function works, my guess is that the jquery.tablednd.js just isn’t being loaded properly.June 18th, 2008 at 11:03 pm
[...] Table Drag and Drop Web site [...]
June 19th, 2008 at 2:33 am
@DenisH thank you for the immediate. i tried to follow your suggestion in firebug and you are right. it is really my problem actually and not with the plugin. i mistakenly typed the filename for jquery.tablednd.js.
i really do appreciate your effort in helping me solved my problem. you are really a great man. keep up the good work.
June 19th, 2008 at 2:38 am
@Denish [thank you for the immediate reply] i mean. sorry for the typo error on the previous post.
June 19th, 2008 at 12:16 pm
Hi,
Having a problem with making this work. File is included without errors but then I try to make a table sortable, Firebug says:
ob.toString is not a function
[Break on this error] var nodrag = $(rows[i]).hasClass(“nodrag”);
js (line 139)
$ is not a function
[Break on this error] var nodrag = $(rows[i]).hasClass(“nodrag”);
Perhaps worth mentioning that Im not using standard “$” but “$j” instead to call jQuery.
Many thanks,
Juraj
June 19th, 2008 at 12:50 pm
follow up
:
I commented out “nodrag” class checks, i.e:
var nodrag = false; //$(rows[i]).hasClass(“nodrag”);
since I wont have any rows which are not draggable anyway. This seems to solve my problem.
Any ideas?
J.
June 19th, 2008 at 12:51 pm
Hi Juraj,
I reckon this is due to the bug in the code to do with the fact that I’ve left $(…) in two places in the plugin. If you look at the post from Foppe it tells you which lines to change. If you change them to jQuery then it should work fine. I’ve fixed this in the alpha of the next release but need to do some more testing before I make it public. Sorry!
June 19th, 2008 at 1:05 pm
Yes I just realised as I wasnt sure what you are allowed to use inside a jQuery plugin and came here to make 3rd post
All working now.
Excellent plugin. Pint of beer for you
Juraj
June 19th, 2008 at 2:52 pm
Not sure if anyone requested this but “refresh” would be useful as well as I keep dynamically adding rows.
Cheers
Juraj
June 23rd, 2008 at 1:40 pm
-
Hi,
found a typo, that has to be corrected on both the website and in the JS-file itself
Please change “serialise” to “serialize” everywhere!!
thx for the plugin anyway
djot
-
June 24th, 2008 at 12:48 am
Hi Dennis,
Thanks for this great JQuery add-on which I am putting to very good use in a Windows Desktop app.
I’ve added: if ( ev.button == 1 && ev.target.tagName == “TD” )
to the mousedown() function as I use a context menu on right click and also don’t feel that drag&drop should work with the right button. Maybe you could add an option for this in the future.
Could you also please include the code posted by Andrew on May 5th, 2008 at 8:05 am which lets us disable table d&d.
Keep up the great work,
Neville
June 25th, 2008 at 4:15 pm
[...] Table Drag and Drop JQuery plugin [...]
June 30th, 2008 at 1:16 pm
djot, ’serialise’ is a perfectly correct spelling in *all* other parts of the world
(just a friendly dig, no offence meant)
Many thanks Dennis for your great work.
Cheers,
Nick
June 30th, 2008 at 7:38 pm
Hey Dennis, I wondering is anyone knows of a way to make the table scrollable inside a scrollable div. I mean just like how window scrolls when I drag to the edge of the window, Is there a way to scroll once I hit the edge of the scrollable div?
Thanks for any help!!!
June 30th, 2008 at 11:50 pm
i am trying to make a drop down table …
everything works fine but i couldn’t figure it out how i can get the id of dropped row.
i can update db table with only one query only if i have the starting row id which i can get easily by using row.id and the dropped row id ( which i don’t know how i can get ???) .
please relpy if there is an easy way to find the dropped row id.
All thanks to Dennis for this very useful plugin
arian
July 1st, 2008 at 6:38 pm
Is there any way to drop rows but ony when you hold mouse on one particular column. I don’t know are mine explanations clear – In standard version if there is few columns, to drag a row you can grab any column and move all row up or down, I want make dragging work only if you grab one column.
Sorry for poor english
July 4th, 2008 at 11:30 pm
[...] Table Drag and Drop JQuery plugin | Isocra (tags: jquery table drag) [...]
July 5th, 2008 at 12:15 am
Table Drag and Drop JQuery plugin | Isocra…
I ve been using JQuery for a while now and really agree with its tag line that it s the The Write Less Do More JavaScript Library We ve also got this…
July 7th, 2008 at 8:58 pm
[...] Table Drag and Drop: Como su propio nombre indica, permite arrastrar mover las filas de una tabla para ordenarlas a gusto del usuario. [...]
July 9th, 2008 at 11:11 pm
Pawel (And Lucas who was creating the dragHandle),
To make only one column do the dragging you can do this:
change makeDraggable line:
if (ev.target.tagName == “TD”)
to:
if (ev.target.tagName == “TD” && ev.target.className == “drag”) {
or… check the ID or another className and then the code will only activate on that specific TD.
July 10th, 2008 at 2:45 am
Forget what I just wrote and look for Famic’s post on “dragger”; much tidier.
July 10th, 2008 at 8:54 pm
Huge thanks!
I am new to CakePHP and Prototype (but I’m a jQuery addict), and had some problems getting it to work on a quite complex page wich used ajax pagination (from CakePHP), ajax form insertion into the same table (with ajax helper) and reloading the whole pagination-div with jQuery, including some visual effects thrown in.
Here’s what I had to do:
).
Make sure prototype and scriptaculous is loaded before jquery and tablednd.js, then execute a javascript-codeblock:
jQuery.noConflict(); right after including the jQuery-files.
Do not use custom noConflict variable-names, stick with the default and it seems to work quite nice (and that’s a lot of js-code working together at the same time!
July 11th, 2008 at 9:59 am
JQuery Drag and Drop…
Rearanjeaza randurile unui tabel prin Drag and Drop cu libraria jQuery…
July 11th, 2008 at 3:34 pm
At long, long last here’s the latest version of the plugin. It now supports drag handles and cleverer serialization. It should also now work properly with Scriptaculous and Prototype.
I had hoped to add in multi-table drag and better support for multiple tbodies, but decided it was better to get this release out than hang on any longer.
DenisH
July 12th, 2008 at 4:35 pm
[...] Table Drag and Drop JQuery plugin | Isocra (tags: jquery javascript plugin tables) [...]
July 13th, 2008 at 4:00 pm
[...] Table Drag and Drop JQuery plugin [...]
July 16th, 2008 at 6:40 pm
Thanks Denish
July 21st, 2008 at 8:07 pm
I am trying to implement a table like table-5 above and when the page loads all of the cells contain the image until I hover over the row then move the mouse. Basically the cells do not look like table-5 until after I hover over each row once. Is this something I need to fix in my CSS code or in the onload of the HTML page?
July 22nd, 2008 at 5:55 pm
Never mind I figured out what I did wrong.
I need to create a blank style to start out with.
July 25th, 2008 at 1:09 am
We wanted to make everything draggable except links and form elements. In particular, we wanted text in the row to drag like everything else. We did this by changing:
if (ev.target.tagName == “TD”) {
to:
if (ev.target.tagName != “A” && ev.target.tagName != “INPUT” && ev.target.tagName != “BUTTON” && ev.target.tagName != “SELECT” && ev.target.tagName != “TEXTAREA”) {
This seems to work, though a full solution would traverse from the current element up until the TD and verify it doesn’t hit one of these elements on the way. This additional check would prevent issues where foo is draggable when it should be a link.
July 25th, 2008 at 1:10 am
“foo” in my previous comment should have looked like <a…><b>foo</b></a>
July 28th, 2008 at 11:47 am
[...] die DnD funktioniert auch einfach nicht. Ich bin dabei anhand folgendes Tutorials vorgegangen: Table Drag and Drop JQuery plugin | Isocra Hatte vielleicht schon mal jemand ein ähnliches Problem? Gruß Thomas __________________ [...]
July 29th, 2008 at 4:58 pm
@DenisH great work on this script, but my question is, im trying to use your example of table 3, when im finished sorting i want to save the new order values to my database, you seem to have done it (sort of) in your example, im new to ajax, is it possible to see the code on how the ajax load is working, since its usiing php to display the new values thats all i really need.
July 31st, 2008 at 1:36 am
hi DenisH, great plugin there, really enjoy it.
I have a problem though, have been cracking my head try to get the re-arranged new position update to the database, using asp, classic asp I mean.
Come across the tips on how to do it in coldfusion, but still couldn’t figure out how to do it in asp, anyone here can shade some light on this?
Thanks guys.
July 31st, 2008 at 1:37 am
Oops..sorry, not sure why my comment appear as posted by DenisH,
. the above comment is from me.
July 31st, 2008 at 7:30 am
Hi Kahfei,
If you need to update a database using ASP, JSP, PHP, ColdFusion or whatever, then you have two choices, you can use an Ajax call to inform the server whenever the user drops a row, or you can have a button that sends a form back to the server so the user can do a “Save”. For the Ajax call, have a look at table-3 to see how that’s done. Once you’ve dragged, the results of the server-side PHP are shown on the right hand side and you can click on the link to see the source. If you use a button, then it would work in much the same way. Put the results of the serialize() call on the end of the URL and the server will get the data you need.
If you were using VBScript (not my usual language, so apologies if it is a bit clunky) you could do something like this:
dim iCount if (request("table-3[]").count > 0) then ' If we've been posted some updates, update the database set oConn = server.createObject("ADODB.Connection") oConn.open sConnStr ' sSQL = "UPDATE mytable SET displayOrder = 0" ' oConn.execute(sSQL) for iCount = 1 to request("table-3[]").count dim rowId rowId = request.queryString("table-3[]")(iCount) if (rowId <> "") then sSQL = "UPDATE mytable SET displayOrder = " & iCount & " WHERE rowId = " & rowId oConn.execute(sSQL) end if next oConn.close set oConn = nothing end ifHope this helps!
August 1st, 2008 at 10:03 pm
>>>0.5 2008-07-11 Now supports having a column as a drag handle
So you mean columns are switchable by dragging now???
August 2nd, 2008 at 7:14 am
No, dragging columns would be tricky because each row would have to be changed. By “drag handle” I mean that you can put an icon or something in a column and then only drag rows using that column. See table-5 above.
August 2nd, 2008 at 10:41 am
Hi DenisH,
Million thanks, will try to adapt that to my code.
August 6th, 2008 at 1:37 am
great thing
one little question..
how can i submit the form via POST? this would be just great – if there’s some easy solution.
tried some jquery-ajax function, but they dint work
thx
August 8th, 2008 at 3:34 pm
Is there a way of detecting an actual change? By clicking on a row and NOT dragging it still makes the ajax call, i am wondering if there is a way to detect whether the row ordering had in fact changed.
August 8th, 2008 at 3:58 pm
One of the things that is still lacking in this plug-in is some sort of tollerance so that a drag of less than, say 5px, up or down wouldn’t trigger the onDrag code–or if you drop the row where it was originally.
For now I’m afraid you’ll just have to remember the original order and then check it before doing the Ajax call. You can do this pretty simply by storing the string returned from serialize as say originalOrder. Then in your onDrop code, call serialize again and see if the new order is the same as the original one. If it is, do nothing, otherwise replace the originalOrder with the new one and call your Ajax.
Hope this helps.
August 8th, 2008 at 4:16 pm
Yep.. i store the original order in the onDragStart event and compare in the onDrop event. Thanks!
August 11th, 2008 at 7:00 pm
Another query… is it possible to remove tablednd from a table using javascript? I want to be able to turn ordering off and on, i can turn it on.. i need a way to turn it off wthout a page reload.
Thanks
August 12th, 2008 at 3:00 am
Hi, im trying to integrate this plugin with another (Flexigrid), however when the format of this table is:
.
.
is it possible to use the tableDnD() function in this way?
August 12th, 2008 at 3:03 am
sorry was trying to write table and tbody, is it possible for the table drag and drop plugin to work in this way?
.
.
August 14th, 2008 at 8:29 pm
Hi. I’m trying to store the original order through the onDragStart event and only update if the original order is different than the order onDrop. I’ve tried a couple different ways with no success. Any help would be appreciated. Thanks!
August 15th, 2008 at 10:29 am
Just a quick note, if you add a semi colon to the end of line 374 you are then able to use Dean Edwards packer to get the plug-in down to 3kb instead of 17kb.
August 17th, 2008 at 7:49 am
[...] Table Drag and Drop [...]
August 17th, 2008 at 7:49 am
[...] Table Drag and Drop [...]
August 19th, 2008 at 9:33 am
[...] Table Drag and Drop – This TableDnD plugin allows the user to reorder rows within a table [...]
August 20th, 2008 at 7:59 am
Hi folks!
I´ve started to use this plugin last week (congratulations to DenisH for his work).
The thing was that I needed to use the tablednd inside a scrolled div.
I´ve made the changes to get it working this way and I will let them here for anyone that has the same needs than me.
best regards to everyone!
——————————————————–
I added a new option to inform the plugin which is the name of the container:
.... serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs serializeParamName: null, // If you want to specify another parameter name instead of the table ID dragHandle: null, // If you give the name of a class here, then only Cells with this class will be draggable containerDiv: null // bottomBorder) { container.scrollTop(container.scrollTop() + config.scrollAmount); } if (mousePos.y jQuery.tableDnD.oldY; // update the old value jQuery.tableDnD.oldY = y; // update the style to show we're dragging if (config.onDragClass) { dragObj.addClass(config.onDragClass); } else { dragObj.css(config.onDragStyle); } // If we're over a row then move the dragged row to there so that the user sees the // effect dynamically var offsetx = jQuery.tableDnD.mouseOffset.y + container.scrollTop() - 10; // this number (the 10 in the line above) is a FIX to adjust the mouseover, feel free to change it to wherever you need var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y + offsetx); if (currentRow) { // TODO worry about what happens when there are multiple TBODIES if (movingDown && jQuery.tableDnD.dragObject != currentRow) { jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling); } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) { jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow); } } } // END NINDAF FIX return false; },August 20th, 2008 at 8:03 am
sorry for the latest post, the code is … i don´t know what happened, i will post a link to the sources late at night,
August 20th, 2008 at 8:05 am
TableDnd in Scrolled Div, Part 1:
adding a new option to the plugin:
this.each(function() { // This is bound to each matching table, set up the defaults and override with user options this.tableDnDConfig = jQuery.extend({ onDragStyle: null, onDropStyle: null, // Add in the default class for whileDragging onDragClass: "tDnD_whileDrag", onDrop: null, onDragStart: null, scrollAmount: 5, serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs serializeParamName: null, // If you want to specify another parameter name instead of the table ID dragHandle: null, // If you give the name of a class here, then only Cells with this class will be draggable containerDiv: null }, options || {}); // Now make the rows draggable jQuery.tableDnD.makeDraggable(this); });August 20th, 2008 at 8:07 am
TableDnd in Scrolled Div, Part 2
replace mousemove function:
mousemove: function(ev) { if (jQuery.tableDnD.dragObject == null) { return; } var dragObj = jQuery(jQuery.tableDnD.dragObject); var config = jQuery.tableDnD.currentTable.tableDnDConfig; var mousePos = jQuery.tableDnD.mouseCoords(ev); //auto scroll the window // FIX TO CHANGE SCROLL TO DIV INSTEAD THE ENTIRE DOCUMENT - NINDAF var container = config.containerDiv; var yOffset = container.scrollTop(); var windowHeight = container.innerHeight(); var y = mousePos.y - jQuery.tableDnD.mouseOffset.y; var upperBorder = container.position().top; var bottomBorder = container.position().top + container.innerHeight(); if (mousePos.y > bottomBorder) { container.scrollTop(container.scrollTop() + config.scrollAmount); } if (mousePos.y jQuery.tableDnD.oldY; // update the old value jQuery.tableDnD.oldY = y; // update the style to show we're dragging if (config.onDragClass) { dragObj.addClass(config.onDragClass); } else { dragObj.css(config.onDragStyle); } // If we're over a row then move the dragged row to there so that the user sees the // effect dynamically var offsetx = jQuery.tableDnD.mouseOffset.y + container.scrollTop() - 15; var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y + offsetx); if (currentRow) { // TODO worry about what happens when there are multiple TBODIES if (movingDown && jQuery.tableDnD.dragObject != currentRow) { jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling); } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) { jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow); } } } // END NINDAF FIX return false; },August 23rd, 2008 at 6:19 am
Hi, when I put div tags between the td tags, I still have functionality but I can only start dragging from the very bottom or very top of the row. I mean that I have to click maybe 1 or 2 pixels from the bottom border. Same applies for the top either. However, I want to start dragging the row no matter where I click (usually the middle). Is there any workaround for that?
August 25th, 2008 at 4:10 pm
Would be helpful to serialize table data to a JS object instead of a string.
serializeTableToObject: function(table) { var result = {}; var tableId = table.id; var rows = table.rows; result[tableId] = []; for (var i=0; i<rows.length; i++) { var rowId = rows[i].id; if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) { rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0]; } result[tableId][i] = rowId; } return result; }August 26th, 2008 at 12:37 pm
Great work DenisH!
Are you by any chance planning an update to the plug-in some time in the near future? I’d hate to see this one lost, without it at least reaching version 1.0!
How much work have you done performance-wise? It seems a bit sluggish on tables containing more than 50 rows.
August 28th, 2008 at 7:40 pm
Hi DenisH,
I must say that jQuery’s plugin is simple, minimalistic and fantastic!. I only want to know: What kind of license is it on? Is it GPL/MIT like jQuery? Can I use it in a commercial / non-commercial proyect?
August 28th, 2008 at 7:44 pm
Thank you so much! This is wonderful!
August 29th, 2008 at 12:50 pm
[...] pode agilizar ainda mais no desenvolvimento do projeto. Um exemplo que usei hoje em um projeto é o Drag and Drop. Veja como o plugin funciona, com apenas uma linha de [...]
August 29th, 2008 at 2:39 pm
[...] lists, but not so many for actual tables. The final solution I used was from an unexpected source, Isocra Consulting, who setup a jQuery plugin for this functionality. The library, TableDnD plugin, is fairly small, [...]
August 29th, 2008 at 4:03 pm
Hi all, just got back from holiday. Quick answers to some of your questions:
1) Yes I am planning to update the plug-in so please keep the comments and suggestions and improvements coming
2) Re licensing, it’s licensed under LGPL so you can use it in commercial and non-commercial software, just please keep the attribution back to here.
September 1st, 2008 at 4:10 am
i am trying to use the tableDndUpdate() to re-initialize the drag-and-drop on a table i’m updating via ajax. i’m having trouble getting it to work. can you explain where to make this call, or give an example?
thanks so much!
September 4th, 2008 at 3:08 pm
Excellent work DenisH – one of the slickest plugins I’ve seen.
Can I just add my request for the onDrop event to be fired only when an actual td move has taken place. I appreciate that the serialize stuff can be employed but it, of course, requires extra code.
Many thanks
September 5th, 2008 at 7:36 pm
Pros: This plugin is really useful and has saved me a bunch of time.
Cons: Thus plugin only acts on hard-coded html, but not objects added dynamically to the DOM by jQuery.
September 5th, 2008 at 8:29 pm
Ignore my last comment. I didn’t read the version history.
September 10th, 2008 at 10:06 pm
Is there an easy way to change how far you have to drag a row to have it swap with the next row?
With taller rows, sometimes you have to drag past the border between the two rows. This interferes with a simple “onhover” styling method, as demonstrated in your .hover() example, and sometimes the JS will consider both rows as being hovered.
In one sense, I think it’d feel snappier to have it instantly make the swap right on the border, but then in other cases I can see why it’d be nice to have a little buffer. Right now it looks like it does a little bit of both.
September 11th, 2008 at 12:59 pm
Hi Nathan,
Unfortunately this isn’t settable and it probably should be. I’d like to make it so that you can set a minimum drag distance as well as controlling this but haven’t had time to implement this yet.
Do feel free to suggest a way of doing this!
September 12th, 2008 at 11:07 am
Hi,
First, thanks a lot for this plugin. it’s marvellous.
I have one question: can i use this plugin for groups/parts of tables?
I want to move, for exemple, your table 5 above the table 4 with all the rows. Is that possible?
thanks,
zelf.
PS: For french people = Si je peux avoir la réponse en français c’est bien aussi ^^. merci.
September 12th, 2008 at 11:41 am
En français:
Salut Zelf, malheureusement ce n’est pas possible de grouper des lignes. Je n’ai pas de mécanisme pour choisir plusieurs lignes. Tu pourrais peut-être mettre des “checkboxes” dans chaque ligne et puis quand l’utilisateur bouge une ligne, tu bouge tout les lignes sélectionné?
In English:
Hi Zelf, unfortunately it isn’t possible to group rows currently. There isn’t a mechanism to select multiple rows. You could perhaps add checkboxes to each row and then whenever a user drags a row you move all of the selected ones?
September 12th, 2008 at 12:14 pm
thank you for your aswer.
I’m not sure it will works because my problem come from the tbodies. i would like to move each tbodies as you do with rows(i dont want to select some rows, i wana move all the rows) AND move the rows in one tbodies.(it is for sub catégories).
Maybe can i modify the plugin but i’m a noob with jquery.
That’s why i’m searching an other solution xD.
Thanks again.
September 15th, 2008 at 6:37 am
Denis,
Thank you so much for TableDnD. It is a fabulous tool. I just ran into an issue with it however and hope you can help. This may be similar to the issue Kai faced on 28-Mar-08. When I used this script on .php pages with the table fully rendered, TableDnD works perfectly. However, when I try to use TableDnD on a table generated via php code it doesn’t get bound to table.
The table is being correctly generated. I verified this by copying and pasting the generated code into a fully rendered page. You can examine it for yourself. The fully rendered page that works is at http://oheller.net/tmp/top10test.php. The generated page that’s not working is at http://oheller.net/Forms/Top10InputForm.php.
What do I have to do to get the generated code to sync up to TableDnD. Do I need to generate the form as an external file and then load it like you suggested to Kai? (I hope not.)
Thanks!
September 15th, 2008 at 6:39 am
Denis,
Thank you so much for TableDnD. It is a fabulous tool. I just ran into an issue with it however and hope you can help. This may be similar to the issue Kai faced on 28-Mar-08. When I used this script on .php pages with the table fully rendered, TableDnD works perfectly. However, when I try to use TableDnD on a table generated via php code it doesn’t get bound to table.
The table is being correctly generated. I verified this by copying and pasting the generated code into a fully rendered page. You can examine it for yourself. The fully rendered page that works is at http://oheller.net/tmp/top10test.php. The generated page that’s not working is at http://oheller.net/Forms/Top10InputForm.php.
What do I have to do to get the generated code to sync up to TableDnD. Do I need to generate the form as an external file and then load it like you suggested to Kai? (I hope not.)
Thanks!
[p.s. pardon any duplicates...I tried submitting this once before but it did not appear.]
September 15th, 2008 at 8:57 am
Hi PeteOH,
You caught me at a good time as I don’t normally have time to debug people’s applications for them. Anyway I’ve just had a look at your two pages using Firefox with Firebug installed. If you’re not using Firebug yet, go and download it and install it. It will revolutionize your web development! Alternatively if you’re using IE, then have a look at IE8 beta which has good developer tools built in apparently.
Anyway, as soon as I looked at your /Forms/ version Firebug told me that there were two errors in the page, one saying that jQuery wasn’t defined and the second saying that $(“#Top10Table”).tableDnD is not a function on line 163 of your code. Having a quick look at the code I think the problem may be simply that you’ve included tablednd_jquery.js before jquery in the one that doesn’t work and you’ve put them the right way in the page that does work.
Given that Javascript is interpreted in order and the TableDnD plugin executes to extend JQuery, it’s important that jquery.js is loaded first.
Hope this helps
September 16th, 2008 at 12:11 am
lol @ nathan at the start of the comments…
ps. Great script! well done =)
September 17th, 2008 at 1:09 pm
I’m not very well in english so let me say it in french. Thanks!
en français:
merci pour ce brillant script. La version avec TBODY correspond très bien avec mon besoin. J’ai voulu intégrer serializeRegexp() pour avoir une réponse du type QUATRE_1 QUATRE_2 QUATRE_3 … CINQ_1 CINQ_2 CINQ_3 … SIX_1 SIX_2 SIX_3 mais j’arrive pas à trouver où mettre le filtre regex. Si quelqu’un peut me montrer comment le faire, si possible avec l’appel de la page de reponse .php (load() non ?) alors je lui serais vraiment reconnaissant.
merci beaucoup
September 17th, 2008 at 6:26 pm
Hi, I’ve noticed that when you try to move one of the rows that’s in a TBODY into a THEAD, it throws an error. This is the error i got from firebug:
Node was not found” code: “8
http://mysite.com/includes/js/jquery.tablednd_0_5.js
Line 275
I think at the very least, it should check to see if they have the same parents and not allow you to move outside of the original parent. So i took the liberty to add that in my code and it works. Starting on line 270 of v0.5, replace the if(currentRow) block with this:
if (currentRow)
{
// TODO worry about what happens when there are multiple TBODIES
if (movingDown && jQuery.tableDnD.dragObject != currentRow)
{
if(currentRow.parentNode == jQuery.tableDnD.dragObject.parentNode)
{
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
}
}
else if (! movingDown && jQuery.tableDnD.dragObject != currentRow)
{
if(currentRow.parentNode == jQuery.tableDnD.dragObject.parentNode)
{
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
}
}
}
Sorry if that didn’t format correctly.
Now it won’t throw an error if you are moving it outside its original parent. This should only be a temporary fix as there should be some established behavior going among THEADs, TBODYs, and TFOOTs. I simply needed it not to throw a js error if you moved the row where it wasn’t meant to go. Any word on when a new version will be out? Pretty slick so far…
Jason
September 25th, 2008 at 5:15 am
If you want ghosting rows its easy but you have to use scriptaculous
Sortable.create(“table1″, { tag:”tr”, containment:["table1"], ghosting:true })
http://talkingcode.co.uk/2007/11/14/drag-and-drop-table-rows-with-ajax-scriptaculous-and-prototype/
Trax PHP Framework
September 26th, 2008 at 11:36 pm
Is there away to get this to update a MySQL database using PHP? Lets say the user moves id 3 to id 1, the mysql table will be updated via Ajax, PHP, MySQL?
Basically the unique id is switched. The html table is populated from the mysql table obviously. I know it require getelementbyid but I can’t get this working.
Thanks.
October 2nd, 2008 at 12:59 am
Here’s my method. (It might not be the best ever, but it works):
// Initalize your table in JS $('.yourtablename').tableDnD({ onDrop: function(table, row) { $.post('main/ajax.php', {'mode': 'reorder', 'ids': $.tableDnD.serialize()}, function(data) { // Whatever you want to do here } }); } }); // My Reorder Function in PHP #================================================ # Save reorder #================================================ if ($mode == 'reorder') { $fields = explode('&', $_REQUEST['ids']); $order = 0; foreach($fields as $field) { $order++; $field_key_value = explode('=', $field); $level = urldecode($field_key_value[0]); $id = urldecode($field_key_value[1]); $db->query('UPDATE yourtable SET l_order="' . $order . '" WHERE id="' . $id . '"'); } }———————-
Note:
———————-
* l_order in the db table is the field that has the order value
Hope it helps!
Cheers,
Terry
October 2nd, 2008 at 11:09 am
I have trouble making this work in combination with scriptaculous and prototype (as a part of lightbox). As long as I include both .js files in my code, the drag and drop functionality does not work (at all, nothing happens, no errors either). I use the newest version of JQuery and Tablednd. What could be the problem? Any help is much appreciated!
October 2nd, 2008 at 2:00 pm
Some additional information:I know Prototype redefines $ and I have tried the noConflict() function + changed every $ to ‘jQuery’, but to no avail (this seems to have no effect whatsoever). The moment I remove the prototype.js file, everything works fine, so the cause of the problem should be near, but I can’t put my finger on it…
October 4th, 2008 at 9:21 pm
Thanks a lot for the nice plugin.
As for the drag-across-multiple-tbodys problem, I believe this fixed it for me: http://gist.github.com/14807
October 14th, 2008 at 5:17 am
Thats excellent.. Is it possible to drag and drop a row from one grid to another?
October 14th, 2008 at 1:59 pm
Is there anything in the works to make the drag and drop work across tables? If so, I would like to have access to it. I am more than willing to help you get it working properly.
October 16th, 2008 at 12:04 am
Hey guys.
Great plugin. Couldn’t make it with jquery ui, so I had to stick with the plugin, which, by the way, rocks.
But a thing I really need that jquery ui’s sortable has and this plugin doesn’t is the “sort” method. Something like onChange, that lets you know every time when a row has changed its position.
Any idea on how to implement that in this plugin?
Thanks,
Dan
October 16th, 2008 at 1:20 am
Hey again.
Solved it myself.
I added a new parameter called onSort.
mods: add to the tableDnDConfig the onSort option as follows:
this.tableDnDConfig = jQuery.extend({
...
...
...
onSort: null,
...
...
}
and then, right before the end of the mousemove function, when checking if we’re moving up or down, after inserting the rows before or after, trigger the onSort config:
config.onSort();,so that the conditional looks like this:
if (currentRow) { // TODO worry about what happens when there are multiple TBODIES if (movingDown && jQuery.tableDnD.dragObject != currentRow) { jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling); } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) { jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow); } config.onSort(); }Helped me a lot. Hope it helps somebody else, too.
Cheers,
Dan.
October 16th, 2008 at 3:37 pm
Hi, is there any way to serialize only certain rows? For example only those with certain class or element inside?
Thanks
October 17th, 2008 at 3:08 pm
Hey DenisH,
Thanks for creating this and sharing it with the world. I was wondering if you could go into further detail about the difficulties in ghosting table rows on drag. From a UX perspective I think some form of ghosting is a necessity, it just doesn’t feel right without it. Looking around at other jQuery d ‘n’ d plugins, I came across Kean Loong Tan’s jTree, a list sorter:
Blog post: http://www.gimiti.com/kltan/wordpress/?p=29
Demo: http://www.gimiti.com/kltan/demo/jTree/
which exhibits the sort of behaviour I’m after.
I had a quick go a repurposing it to work with a table (little more than a search and replace on the ul and li references to table and tr) and in Firefox 3 and the latest Webkit at least it seems to work:
http://gist.github.com/17431
What are the reasons for not being able to use the same techniques on a table/tr? I understand that pulling the tr out of the table while dragging would put the html into an invalid state but a temporary wrapping table element could sort that. I guess there’d also need to be a few clevers to maintain the same column widths as in the original parent table plus maybe the addition of a blank row between the hovered rows to act as a drop destination. Am I missing something? Is it getting it to work in IE?… it’s IE isn’t it… a wise man once said “it only takes one turd to ruin a pool party”. In my experience IE is invariably that turd.
Cheers,
James.
October 17th, 2008 at 5:54 pm
Hi,
today i’ve been trying to implement the onAllowDrop and it didn’t work at all. The first parameter (that was supposed to be my dragged row) wasn’t a valid row. After spending some time I realized the what was being passed to the onAllowDrop function as the first parameter wasn’t a row, it is rows array of 1 element. So, to pass the right thing to the function I had to add [0] to draggedRow array :
findDropTargetRow: function(draggedRow, y) { ..... if (config.onAllowDrop) { if (config.onAllowDrop(draggedRow[0], row)) { return row; } else { ....Now, onAllowDrop works at it should.
Thanks for your great plug-in, I find it quite usefull.
Pau.
P.D: Excuse my english.
October 21st, 2008 at 11:04 am
Thanks for this nice plugin! Like Andrew on May 5, 2008, and Fiaz on Aug 11, 2008, I would also like a way to turn this off from JavaScript.
Why? Because I have a legacy way of reordering the table rows that don’t require JavaScript, and I’m not ready to remove that just yet. Browser compatibility is a high priority for me. But the methods interfere with each other, so if anybody uses the legacy way I want to disable the drag-n-drop functionality.
http://www.lysator.liu.se/~ceder/jquery.tablednd.1.patch is my attempt to implement this. I have been using jQuery for less than a week, so it is probably not so good. In particular, I don’t like that I remove *all* event bindings. It should be possible to just remove the events that was previously added. But as long as nothing else adds event handles, it seems to work. Minimally tested in IE 7, Firefox 3 and Google Chrome.
October 23rd, 2008 at 8:39 pm
Thanks for the great plugin!
I made 2 changes to the script to include a class called “no_drag_drop” which allows neither dragging or dropping:
var nodrop = jQuery(row).hasClass("nodrop"); var nodragdrop = jQuery(row).hasClass("no_drag_drop"); if (! nodrop && !nodragdrop) {and:
var row = jQuery(this); if (row.hasClass("nodrag") || row.hasClass("no_drag_drop")) { //dont do anything } else {I think this will be useful if headings are stored in the first row of the table so it should always stay at the top.
October 24th, 2008 at 11:12 pm
How a single cell can drag and drop… pls help.
-Shaon
Open tutor Admin
http://intelisoftbd.com/forum/
October 30th, 2008 at 12:37 am
Great stuff!
I added a delete button to each row. When it is clicked, I put up a confirm dialog to let the user confirm that he wants to delete the row. I find that if the user clicks “cancel”, TableDND is still dragging the row in which the delete button was placed. This makes sense, since the whole row is draggable. Is there a way to mark particular cells within a row as “nodrag”? I tried adding the nodrag class to these cells, but it didn’t appear to be noticed by TableDND.
October 30th, 2008 at 10:38 pm
I found the answer – just use bind and the methods to prevent event bubbling.
$("#theCellID").bind("mousedown", (function(event){ if (confirm("Delete this food?")) { $(this).parent().remove(); } event.stopPropagation; return false; }));October 31st, 2008 at 6:53 pm
[...] the javascript that comes with the Rails distribution, but for this case I decided to go with the Table Drag and Drop JQuery plugin, as it had the right combination of functionality and ease of use. Once the plugin is in your [...]
November 6th, 2008 at 4:10 pm
Table Drag and Drop JQuery plugin…
I’ve been using JQuery for a while now and really agree with its tag line that it’s the “The Write Less, Do More, JavaScript Library”. We’ve also got this code for dragging and dropping table rows that has proved very popular, so it seemed na…
November 7th, 2008 at 6:31 pm
Is there any way of stopping the onDrop function from firing if no rows are reordered? The code seems to fire even if you just click on the row without dragging it.
This is a minor point. Great plugin guys.
November 7th, 2008 at 6:42 pm
I also wanted to mention that I see not being able to drag between multiple tbodies as a feature and not a bug. I use the tbodies to group rows and rows can only be reordered within their group.
I hope that this”bug” isn’t fixed or, at least, I hope that you can set the desired functionality via a parameter. AllowDragBetweenTBodies = true/false.
November 11th, 2008 at 1:05 pm
this is a great tool, thanks for it.
I made a very small modification, what i think is useful:
at the end of the mousemove function after the changing of the rows:
if (config.afterDrag) {
config.afterDrag(dragObj, currentRow);
}
with this i can catch the event after the rows are changing, but the mouse button isn’t released.
Maybe a bigger part of the code can help somebody:
if (currentRow) {
// TODO worry about what happens when there are multiple TBODIES
if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
} else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
}
if (config.afterDrag) {
config.afterDrag(dragObj, currentRow);
}
}
November 13th, 2008 at 8:53 pm
I need the ability to add and remove rows, still keeping the possibility to save the content of the rows and in the current order.
So what I can’t figure out is how to be able to add and remove rows but still be able to use the rest here for saving.
Any suggestions?
November 15th, 2008 at 10:00 pm
FYI:
if i’m dragging a row up and go above the top row in tbody, firebug catches this error:
Node was not found” code: “8
jquery.t…nd_0_5.js (line 275)
jQuery.tableDnD.drag…jQuery.tableDnD.dragObject, currentRow);
it does not present any usability problems (i’m FF 3+), so i’m just letting you know.
thanks for a great plugin!
November 15th, 2008 at 10:10 pm
i set up a page that lets you turn on/off reordering, so i needed to unbind or destroy .tableDnD
ended up with
$("#myTable tr").unbind().css({cursor: "default"}); unbinding the mousemove and mouseup events (on line 114 of the plugin code) from $(document) worked also, but this was cleaner. to get the on/off functionality working, i used jQuery's one() method.. here's the basic format function setupTableDnD() { $("#myTableControl > span").one("click", function () { $("#myTable").tableDnD(); $(this).one("click",function () { $("#myTable tr").unbind().css({cursor: "default"}); setupTableDnD(); }); }); } setupTableDnD();enjoy!
November 17th, 2008 at 11:13 am
me again.
here’s a link to some work i’ve been doing on the multi-table deal.
http://teddevito.com/test/testTables.php
the fun stuff
—–
add rows
add and remove nested tables
move the nested tables around
move rows in and out of nested tables
the key was to not use the native dom method table.rows because it only returns (“table > tbody > tr”) and not (“tr”,table)… plus a bunch of index referencing…
the incomplete stuff
—–
doesn’t work in MSIE (could be any number of errors. i’m not real experienced…)
i’m sure i’m making some major violations to the DOM… don’t take my work as sound – test it yourself (and give me feedback!)
on the bright side, FB isn’t throwing errors any more, so it’s a start and great proof-of-concept.
it won’t drop rows above or below a nested table when it’s all the way to the top or bottom because it tries to put it inside.
—a few ideas here: use a placeholder, use conditionals and a different jQuery insert strategy, track which row and be more precise with control at the top and bottom…
also won’t let me put rows into a nested table that only has the heading row. it doesn’t seem to see any available nodes there or something…
anyway, Thanks Denise and Isocra for getting this going.
it was a huge learning experience (took me all day to do this… i’m not very experienced) and an even bigger waste of time… but oh well
you’ll notice i renamed the object and methods… only for clarity so i can reference the different files and keep my eyeballs straight. it’s annotated to show variations.
November 17th, 2008 at 11:47 am
Great work!
Now jquery is clearer than before!
Andrea
November 18th, 2008 at 1:21 am
fixed most of the errors mentioned above and styled it to show the hierarchy within the nested tables. have to move on to other development on the project, but i’ll check back here.
i would love it if someone could help debug the MSIE performance.
as mentioned before, objects and methods are renamed but well annotated (renamed so i could work on new stuff without conflicting with Denise’s working plugin).
there are no serialize methods. only stuff to create a nested table hierarchy. only tested in FF 3+.
November 18th, 2008 at 9:04 am
Hey! Thx a lot for your great work! I used your tableDnD several times, without any problems, works like a charm.
Till today. I have to combine my table with the http://www.webtoolkit.info/scrollable-html-table.html scrolltable plugin. For this, I have to insert into my table a thead and tfoot. So far so good.
After those changes I’m still able to drag and drop, but the AJAX request is no more working. After some search I found, that the positions of the rows are messed. The “new position” starts with 0, the “last position” with 1. I corrected this behaviour within the line “var rows = $(table).eq(0).children().eq(1).children();”
This works for the first drag and drop: After reload of the PHP-site, new positions are inserted in the database correctly. BUT, if I do more than one drag and drop before I reload the page (or check changes in den database), the positions or the id’s are messed. (e.g. the positions have the order 1,2,2,4.)
Please, could you help me with this problem? What am I doing wrong? How should thead and tfoot be implemented to work?
November 19th, 2008 at 10:11 pm
Hi Denis,
First of all, fantastic plugin! Easy to use and integrate!
However, doesn’t seem to work if elements of the table I’d like to add dragg-n-drop functionality to contain complex structure of elements. Also tried to use the your plugin in a modal dialog box (using another jQuery plugin called Boxy) – so far no luck. Do I need to do anything special to enable it in a modal box?
November 19th, 2008 at 10:14 pm
sorry, your comments box must be stripping html.. hehe.. the above was meant to be “TD elements of the table I’d like to add dragg-n-drop functionality to contain complex structure of DIV elements”
November 26th, 2008 at 9:21 am
NEW – Problem!!!! – -
Hi guys,
It a great!! pluggin. It is working for me also… But, the problem my table is inside a div which gets updated using AJAX.
When I load the table using AJAX the DRAG drop Doesnt work.
Ant suggestions ?? ?
November 30th, 2008 at 9:13 am
@Dharmendra: There could be only one reason: After the ajax request you have to initialize the drag&drop function again. Just call that function within the callbackfunction of the request. E.g.: $.ajax({type:”POST”,url:”go.there.php”,data:”bla=bla”, success:function(){ drag&drop_function() }});
December 2nd, 2008 at 4:05 am
I’m trying to incorporate this plug in with a system written almost entirely in PHP. What I want to do is to resort rows on a screen and when I click my update button, I want to be able to interrogate the current order on the screen.
There is one short example of how to do this and it looks like this:
<?php
$result = $_REQUEST["table-3"];
foreach($result as $value) {
echo “$value”;
}
?>
Problem is that I get nothing returned in $result! For all the talk about serialize on this page, it’s always doing it with a JavaScript alert which is less than useful when you want to use the information programatically.
I’m pretty weak on Javascript so I’m sure I’m missing something here ..
Can anyone help?
Thanks!
December 3rd, 2008 at 5:39 pm
hi..!!!! I used this great scritp on a site.. and works great… but when I add the serialize function thsi stop to work on explorer..
help me please..!!!! 
I dont know what to do without the serialize…
here I copy me simple script…
$('#list-container').tableDnD({ onDrop: function(table, row) { document.getElementById('resultado').value=$('#list-container').tableDnDSerialize() ; }, }); $(\"#list-container tr\").hover(function() { $(this.cells[0]).addClass('showDragHandle'); }, function() { $(this.cells[0]).removeClass('showDragHandle'); }); });December 3rd, 2008 at 5:55 pm
the previous comment contain two slashes on ids hove function but are only to scape php..
helpme please.. :S
December 3rd, 2008 at 6:42 pm
woooooorrrrkssss!!!!!!! sorry… a simple mine error..!!! can delete my coments if you want..!! this script works great..!! congratulations..!!!!!
December 4th, 2008 at 10:34 am
Hello,
Is it possible to move the table rows from one table to another? If yes then how? Please help me. Thanks in advance.
December 4th, 2008 at 6:51 pm
Is there any way to add dragging functionality to only one row? For instance, if you’d already done .tableDnD to your table, but then you added a new row to it, and you didn’t want to re-do the tableDnD?
December 4th, 2008 at 6:53 pm
Nevermind, just discovered tableDnDUpdate(); thanks!
December 5th, 2008 at 3:21 pm
I wonder if you could advise in making this work, the idea is to save the new order of rows in mysql.
my code goes like this:
$(document).ready(function() { $('#table_a').tableDnD({ onDrop: function(table, row) { $('#table_a').tableDnDSerialize(); }, }); }); <? $i = 0; $num=mysql_numrows($result); while(($catpage = mysql_fetch_object($cate_result))||($i < $num)){ echo "" . $catpage->title . ""; echo "id . "'>"; } ?>THE update.php PAGE LOOK LIKE THIS
<?php mysql_connect("----") or die(mysql_error()) ; mysql_select_db("---") or die(mysql_error()) ; $first=$_POST['row_id']; $second=$_POST['gal_id']; $i = 0; while ($i < $first) { $bookinfo= $_POST['row_id'][$i]; $id = $_POST['gal_id'][$i]; $query = "UPDATE table SET `dis_order` = '$bookinfo' WHERE `id` = '$id' LIMIT 1"; mysql_query($query) or die ("Error in query: $query"); print "$bookinfoUpdated!"; ++$i; } mysql_close(); ?>December 5th, 2008 at 3:25 pm
something happend with my post, the while statement goes like this
while(($catpage = mysql_fetch_object($cate_result))||($i < $num)){
echo . $catpage->title . ;
echo id . >;
}
December 5th, 2008 at 3:26 pm
my lines are erased as soon as i submit my post but the echo inside the while generates the colums for each row in mysql
December 5th, 2008 at 3:28 pm
everything seems fine only that when submiting the form i refreshing the table the order of appearance stays the same
December 7th, 2008 at 9:11 am
I Don’t think you have to serialize the table in order to save the order to the database.
Instead, You can put a hidden inputs, with the same name – as an array( i.e ‘IDorder[]‘ ),
And giving them the matching values (IDs).
In the server side, after submitting the form, do :
And the IDs will be echoed with their order, The rest is to save everything to the database…
December 8th, 2008 at 10:25 am
Hey,
I’ve been wondering if it’s possible to make it work like so:
When I click on a dragable row and move it, it just ‘hovers’ above the other cells without phisically moving
them like it does in the original method, and when I’ll release the row – it will appear in the position (if not ‘nodrop’) and
the row that was there will be moved to the place of the row I just moved.
This will fix the problem when I drag a row and all the others rows are moving accordingly.. It’s quite confusing where I use it.
If anyone has a quick way of doing it i’d love to hear.
Thank you all and keep up the great work!
December 8th, 2008 at 1:29 pm
I use it with Live query as well but for me it doesn’t work well :
I have a table that use Pagination : http://plugins.jquery.com/project/pagination
I set the number of line to view dynamically (using an input).
So each time I change it it refresh thet table. And each time I navigate in the table using pagination it reload the datas.
So I needed something like Live Query to keep the DnD alive. But It doesn’t work…
It’s weird cause I don’t know who is wrong.
December 9th, 2008 at 2:55 am
i am new at this plugin, thanks a lot… i am little confused all the code… maybe its simple question but i am not sure… how do i drag td elements also, all the cells dragable i mean to other cells, not only trs.
thanks in advance
December 9th, 2008 at 10:39 am
Hi,
When i add a line in my table by a JQUERY append, this line is not recognized by your script.
How to fix this problem ?
December 9th, 2008 at 2:55 pm
SMalldevil > use liveQuery
http://brandonaaron.net/docs/livequery/
It should helps
December 9th, 2008 at 2:59 pm
luar gomez > Only TR are draggable. You should rather see the jQuery UI libs if you want to drag TD.
http://docs.jquery.com/UI/Draggables/draggable
http://docs.jquery.com/UI/Droppable
December 9th, 2008 at 5:48 pm
Spir > Have you already use livequery for this table drag and drop ? Have you a demo script ?
December 10th, 2008 at 7:04 am
because with my custom script doesn’t works http://inova.tech.free.fr/LIVEQUERY/ help me.
December 11th, 2008 at 7:37 pm
Hey Everyone,
Great plugin Denis!
I noticed someone asked earlier if it was possible to drag multiple rows, to which Denis replied the current version doesn’t handle that.
I was curious if any one has since come up with a hack/solution to get this to work? I have tried using the onAllowDrop callback, but can’t quite get it to work. I think my situation is somewhat more simpler than having to drag and drop an arbitrary selection of rows. I would like to be able to drag a row as well as the row directly below it.
My table looks something like:
row A: | account | label | value | unit | currency |
row B: | secondary row for details | <- spans all columns
row C: | account | label | value | unit | currency |
row D: | secondary row for details | <- spans all columns
So when I drag row A, I want to drag A and B. Additionally, a row can never be inserted between rows A&B or C&D, but can be inserted above A, below D, or between rows B&C. I can also guarantee that these rows always come in pairs.
If anyone has any ideas, I would be extremely grateful.
December 12th, 2008 at 5:13 pm
Just an update to the comment I posted yesterday
Since what I wanted to do was very specific to this one page in our webapp, and since my problem is fairly well defined, I extended the tableDnD JS and tweaked it to suit my situation, though there’s still some issues with it.
I created a new JS file and inside of it have:
Object.extend(jQuery.tableDnD, {
dragObject2: null, // this is going to represent the row below the row I’m dragging
makeDraggable:function(table) {
// …
jQuery.tableDnD.dragObject = this.parentNode;
jQuery.tableDnD.dragObject2 = document.getElementById(’secondary_’ + this.parentNode.id); // this line is new and explicitly references the ID prefixes I use on my page
// …
jQuery.tableDnD.dragObject = this;
jQuery.tableDnD.dragObject2 = document.getElementById(’secondary_’ + this.id); // this line is new and explicitly references the ID prefixes I use on my page
// …
},
mousemove: function(ev) {
// …
var dragObj = jQuery(jQuery.tableDnD.dragObject);
var dragObj2 = jQuery(jQuery.tableDnD.dragObject2); // this line is new
// …
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject2, currentRow.nextSibling);
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, jQuery.tableDnD.dragObject2); // this line is new
// …
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject2, currentRow);
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, jQuery.tableDnD.dragObject2); // this line is new
// …
},
mouseup: function(e) {
// …
var droppedRow = jQuery.tableDnD.dragObject;
var droppedRow2 = jQuery.tableDnD.dragObject2; // this line is new
// …
jQuery(droppedRow).removeClass(config.onDragClass);
jQuery(droppedRow2).removeClass(config.onDragClass); // this line is new
// …
jQuery(droppedRow).css(config.onDropStyle);
jQuery(droppedRow2).css(config.onDropStyle); // this line is new
// …
jQuery.tableDnD.dragObject = null;
jQuery.tableDnD.dragObject2 = null; // this line is new
}
});
The // … comments represent original code from the respective methods which I excluded to make this comment post more clear.
These modifications move a row’s secondary row as I drag a main row around the table.
I still haven’t solved the problem of preventing a row to be dropped between a row and its secondary row (e.g. between row A and B in my previous comment.) Also, using the row names in my previous comment, I can’t move Row A&B below row D if D is the last row of the table. I’m hoping to fix this soon. At least I’m one step closer to what I want. I’ll post other modifications I make once I get everything else working.
If anyone sees any ways to improve this, let me know.
Thanks
December 12th, 2008 at 6:19 pm
I forgot to mention that two of my lines in the previous post were slightly modified from the original
in my overridden mousemove function,
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject2, currentRow.nextSibling);
appears as the following in the original method:
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
and
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject2, currentRow);
appears as the following in the original method:
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
December 15th, 2008 at 3:34 pm
SMalldevil> See this. But I had some issues setting it.
$(document).ready(function(){
$(“#table-1″).livequery(function(){
$(this).tableDnD({
… options …
});
});
});
Bonne chance
December 17th, 2008 at 5:56 pm
Hello,
There is a method to update the table after adding or deleting data.
So after every load or pagnation we can do
jQuery(“#mytable”).tableDnDUpdate()
This will update the new added/deleted data. It is not needed in this case to use livequery.
Sometimes it is good to read the docs.
Regards
Tony
December 27th, 2008 at 7:01 pm
Very nice! Thank you very much
that could be useful for my new projekt
December 30th, 2008 at 11:42 pm
Wow you saved my day… thank you so much. I thought i was going to have to transform my table into an unordered list and use the sortable() function from jQuery UI. But this has saved me so much time. Kudos!
January 7th, 2009 at 2:25 am
Thanks for that great script and for the new dragHandle.
I’m using your script in my WordPress plugin Admin Management Xtended to change the order of pages: http://www.schloebe.de/wordpress/admin-management-xtended-plugin/
Works like a charm. Great work!
January 8th, 2009 at 5:53 pm
Hi, im new on this blog, but i have a problem with the jquery dragg option..
im doing like a Mac dashboard on website and im trying to show some graph but i can´t dragg the widgets insted of that when i choose one of them the indicator stay stuk with the widget.
this is the the widget declaration i hope that somebody could help me
var chart = new FusionCharts(“../dmkitimages/MSBar2D.swf”, “ChartId”, “350″, “375″, “0″, “0″);
chart.setDataURL(“../dmkitimages/Data/MSBar2D.xml”);
chart.render(“chartdiv”);
January 8th, 2009 at 5:54 pm
var chart = new FusionCharts(“../dmkitimages/MSBar2D.swf”, “ChartId”, “350″, “375″, “0″, “0″);
chart.setDataURL(“../dmkitimages/Data/MSBar2D.xml”);
chart.render(“chartdiv”);
January 16th, 2009 at 11:58 am
In my table, i have 3 rows selected with class=’sel’. I want to drag only these rows. How do I do it?
January 16th, 2009 at 3:15 pm
The regular expression doesn’t work…
is passed as “item-1″, and not “1″…
Maybe the error is about at row 360
result += tableId + ‘[]=’ + rows[i].id;
this should be:
if (rowId) result += tableId + ‘[]=’ + rowId;
this one works to me…
January 17th, 2009 at 5:05 pm
so can i do that in vb forums
January 18th, 2009 at 5:13 pm
[...] using jquery plugin for drag and drop.. may be if you can see the page you can understand better http://www.isocra.com/2008/02/table-…jquery-plugin/ in simple words i am updating the new file sequence after i am done changing its old position by [...]
January 20th, 2009 at 8:44 pm
Hello,
I’m having some IE-specific issues with dragging rows. I have a table, where the first cell of each row is used for dragging the respective row. I also have the ability to insert a new row in the table, which is simply done by constructing the HTML for the row, then inserting it using something like jQuery(someRow).after(newRowHTML); After inserting this new row, I call tableDnDUpdate() to make this new row draggable. I verify that this new row also has the correct “draggable” class name that all other rows have. In FF and Safari, I can drag this new row. In IE, however, when I go to drag one of these new rows, it fails, and instead highlights all of the text in that row and other rows as I drag the mouse up or down. Rows which existed before my initial call to tableDnD() can be dragged without any issues.
Am I doing something wrong in this scenario? Has anyone else had this issue?
Thanks!
January 22nd, 2009 at 7:13 pm
I have since resolved this issue. When building the new row to insert, I used a specific (hidden) row’s innerHTML as a starting point for the guts of the new row I was inserting. Even though I changed the ID references of all elements in this new row to differ from those in the source row, the new row still seemed to maintain the “on drag” behaviour the source row had. When I removed the nodisplay styling from this source row, inserted a new row, and dragged the source row, the new row would move instead.
Once I realized what was going on, it was a simple fix. I omitted the drag class handle for this special row, and manually added the drag class to all newly inserted rows.
January 24th, 2009 at 7:43 am
cool work
January 24th, 2009 at 6:02 pm
what about a reorder with sublevels??
Example:
Main 1 Main 2 Main 3 Sub 1 Sub 2 Sub 3 Main 4 Sub 1Great job!
January 26th, 2009 at 5:10 am
AWESOME.. i’ve been been stuck with scriptaculous’ sortable serialize for years, and i’m SO happy to find a jquery equivalent.
I really liked the dragHandle in table-5, but the handles were appearing on rows with “nodrag” (such as headers). The quick and dirty workaround:
$("#sort_table tr").hover(function() { var nodrag = $(this).hasClass("nodrag"); if (nodrag == false) { $(this.cells[0]).addClass('showDragHandle'); }; }, function() { $(this.cells[0]).removeClass('showDragHandle'); });January 26th, 2009 at 9:36 pm
Has anyone got this to work with the new JQuery 1.3 release? It does not seem to want to work for me.
Any ideas would be great! Thanks.
January 27th, 2009 at 5:32 am
I want to disable grabbing a row while the ajax is processing – - any quick way to do this?
January 27th, 2009 at 6:20 am
Thanks for this great plugin…. But im facing one problem that this plugin is working on firefox but not on ie ….
January 27th, 2009 at 12:20 pm
This plug problem with scrolling. Here is my code
$(document).ready(function() { // Initialise the table $("#table-r").tableDnD(); $("#table-r tr:even").addClass('alt'); $("#table-r tr:even").addClass('blue'); $("#table-2 tr:even").addClass('alt'); $("#table-2 tr:odd").addClass('blue'); $("#table-2").tableDnD({ onDragClass:"myDragClass", onDrop:function(table,row){ var rows = table.tBodies[0].rows; var debugStr = "Row dropped was "+row.id+". New order:"; for(var i=0;i<rows.length;i++) { debugStr += rows[i].id; } $("#debugArea").html(debugStr); }, onDragStart:function(table,row){ $("#debugArea").html("Starting draging row "+row.id); } }); }); 1 One 2 Two 3 Three 4 Four 5 Five 6 Six 7 Seven 8 Eight 9 Nine 10 Ten 11 Eleven 12 Twelve 13 Thirteen 14 FourteenI need this urgent for my project. Please help me.
January 27th, 2009 at 12:22 pm
Hi all,
When i am trying to drag with in the scroll, it will not work properly.
suresh.p
January 27th, 2009 at 3:52 pm
Crap. Have any of you tried this on IE 8???
All the examples on this page behave how my pages do using this plugin on IE8 – You’ll notice that you can still drag and drop rows, but you must have your mouse significantly below the row you want to move.
January 27th, 2009 at 9:54 pm
Yeah…I’m experiencing the same issues in IE8…just when I thought I had a reliable option for sorting!
January 28th, 2009 at 8:16 pm
Maybe this has been address and I just missed it. How would I set this up to not drag the first column? I want to leave the information in the first column intact no matter what rows have been moved.
January 28th, 2009 at 8:30 pm
Let me word my question differently. How can I keep the functionality as is, but not move the first cell in each row?
January 29th, 2009 at 4:31 am
Hi to all,
Yes, this is a great plug in.., but there is some bugs. When i am trying to drag rows in a scrolling div, then auto scroll is not working. If anybody knows how to fix this problem for this plug in, please let me know, it is too useful for my project.
Thanking u
suresh.p
January 29th, 2009 at 2:52 pm
[...] features, they perform much better than what the ASP.NET ajax library. Recently I also tried the Table drag and drop plugin, which allows you to change the row positions of a table; and guess what it works like a [...]
January 29th, 2009 at 9:29 pm
Here is the code i used to reorder my forum topic
//js
$(document).ready(function() { $('#table-topic').tableDnD({ onDrop: function(table, row) { var order= $.tableDnD.serialize('id'); $('#topic-order-success').load("forum/topic-order.php?" + order); } }); });//table
echo""; echo"Topic nameDescriptionAccessAction"; while($row=$db->fetch_array($result)){ $row[topic_lock]==0?$access="All":$access="Read only"; echo"$row[topic_name]$row[topic_desc]$accessDelete"; } echo"You can re arrange topic by draging"; echo""; echo"";//topic-order.php
$i=1; foreach($_GET['table-topic'] as $key=>$value) { $value=intval($value); $db->query("UPDATE {$prefix}_forum_topic SET topic_order = $i WHERE topic_id = $value"); $i++; } echo"updated succesfully";February 4th, 2009 at 3:10 pm
Hi,
Are you going to update your plugin to work with jQuery UI 1.6 (currently at rc6)? It currently doesn’t work for me (although my same code works w/1.5.3).
Thanks,
Eric P.
February 5th, 2009 at 10:25 pm
Hi,
Could someone help me out and post me how can I change the color of a row when I am moving it.
Something like here in the examples. I think is getting done via CSS, but I can’t figure it out!
Thank you very much!!!
February 6th, 2009 at 12:17 am
Nevermind,
I figured it out!!!
Thanks….!!
February 9th, 2009 at 1:08 pm
[...] magic to do the drag and drop re-ordering and Ajax save with a bit of help from jQuery and the Table Drag n Drop jQuery plugin from Isocra. Drag the rows then to check it’s working you can refresh the page and the row you dragged [...]
February 12th, 2009 at 10:04 am
Hi,
I tried this work fine with plan foms,
when i add ajax.pro class method this won’t work.
ex. AjaxPro.Utility.RegisterTypeForAjax(typeof(forms_frmdragdrop));
then the above swap row script stop working.
Please Advice
February 12th, 2009 at 6:23 pm
Is it possible to drag from one table to another table of the same format.
I have a Parent-Child DataTable and the second row of the Parent record contains the child table.
What i need to do is to allow move a child to a different parent.
I was able to do so using YUI but i’m working on a new project and used JQuery. Now the customer wants that functionality … of course.
I don’t want to go back to YUI “just” for that.
Thanks
For example, when you serialize, the result could be 2.1 3.1 2.2 2.3 1.2 2.4 2.5
I can wrap this up into something like table1=(2.1 3.1 2.2 2.3 1.2 2.4 2.5)or something
February 17th, 2009 at 8:18 pm
Hi,
Could someone help me out and post me how can I change the color of a row when I am moving it.
I want to see rows change the color based on row dropped. So colors are alternating again when user picks up and drag the row
Thank you very much!!!
February 18th, 2009 at 7:40 pm
Muchas gracias por el aporte. Desde Paraná – Entre Ríos – Argentina agradezco el plug in.
Felicitaciones (congratulation)
Thank you very much!!!
February 20th, 2009 at 7:11 pm
Hey, this works fine. I had a question about using javascript to make additions to the table. On an ajax page I am making, I allow the user to create a new entry, which- if successful- inserts a new TR into the table (using the latest version of jQuery)
This new TR can’t be moved. I tried calling the tableDnD function on the table again, to see if it would re-examine the structure, but nothing changed.
Is there a way to remove the tableDnD() status from a table? I was thinking if I stripped it, and re-assigned it, maybe that would be a work around.
February 20th, 2009 at 7:12 pm
Whoops, I just noticed tableDnDUpdate(); mentioned earlier. Sorry!
February 23rd, 2009 at 1:48 pm
can u plz tell me how this drag drop can be maintained in Gridview in ASP.Net 2.0?
February 23rd, 2009 at 1:58 pm
i want to interchange sequnce id of my rows of gridview.
i hv to maintain it for differetn users and dynamically.
February 23rd, 2009 at 7:21 pm
When I get TR html from an ajax request and append it to the table, I call $(“#myTable”).tableDnDUpdate() in hopes that I can then drag that row around too, but it is fixed. All the other rows continue to be able to move though. Is there an issue with how you should add rows to the table so the update function will work? I just do:
$(“#myTable”).append(“stuff”);
$(“#myTable”).tableDnDUpdate();
I am using Firefox 3.0
February 25th, 2009 at 5:10 pm
If you use zebra styling on your table, be sure to remove all odd and even classes before reapplying onDrop.
onDrop: function(table, row) {
$(‘#myTable tr’).removeClass(‘even odd’);
$(‘#myTable tr:even’).addClass(‘even’);
$(‘#myTable tr:odd’).addClass(‘odd’);
},
February 26th, 2009 at 4:56 am
@euro and others who’ve had troubles with data vanishing for PHP in the $_POST array after a form submission: I just by whim decided to put the and tags OUTSIDE THE TABLE, and that seemed to do the trick. For some reason, the DOM rewriting drops them outside of the form if the form tag doesn’t surround the table. Hope this helps.
February 27th, 2009 at 9:51 pm
Hello, I had a problem with your plugin.
When there were several tables inside the drop was tablela error.
>> Node was not found” code: “8
http://***/jquery.tablednd_0_5.js
Line 275
I bypass the error by adding this condition:
if (this.parentNode.parentNode == table) (
line 144
Thus:
} else { // For backwards compatibility, we add the event to the whole row var rows = jQuery("tr", table); // get all the rows as a wrapped set rows.each(function() { if (this.parentNode.parentNode == table) { // Iterate through each row, the row is bound to "this" var row = jQuery(this); if (! row.hasClass("nodrag")) { row.mousedown(function(ev) { if (ev.target.tagName == "TD") { jQuery.tableDnD.dragObject = this; jQuery.tableDnD.currentTable = table; jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev); if (config.onDragStart) { // Call the onDrop method if there is one config.onDragStart(table, this); } return false; } }).css("cursor", "move"); // Store the tableDnD object } } }); }March 2nd, 2009 at 8:19 pm
Ack… nevermind my comments. jQuery UI isn’t even a dependency for this plugin. I goofed.
Sorry!
Eric
March 4th, 2009 at 10:41 am
Why should I use this plugin? ui.sortable can be applied to tables and does the trick. *confused*
March 5th, 2009 at 1:53 pm
I’ve been playing with this plugin for a couple of days..quite nice however I was wondering a few things from using it and reading some of the above comments:
1. Has this plugin been updated since July of 2008? That appears to be the latest version. Any plans for an update?
2. I noticed that when using a checkbox column, the checkbox does not keep its checked state after dragging it. This happens in IE. Any ideas?
3. Noticed in IE8 the dnd is a little off.
March 6th, 2009 at 11:32 am
Very useful plugin, thanks.
I have an issue with divs: If I put a div containing text inside a table cell, I can’t move that row by dragging the text. Any ideas?
Regards
Oliver
March 7th, 2009 at 9:14 pm
Hi, Good plugin.
I would like the row that receives the drop to not move. Therefore the user will only see the row being dragged moving. When it is dropped I will work out which row received the drop.
Is there anyway of stopping the droppable rows from moving when a row is being dragged?
Regards Ian
March 9th, 2009 at 9:34 pm
Unbelievable plug-in!! I’m a PHP hack (at best) with NO JavaScript skills AT ALL! This plug-in has saved me hours (days? weeks!?!) of frustration with a one-time need (needed to re-order questions in various parts of a test).
So simple – used the serialize() function (thank you!!!) to create (actually ‘replaceWith) a HIDDEN input value that was the serialized result of the user’s actions (on every ‘onDrop:’ ). Hitting the Submit button sent the new order – updated the database and I’m done.
Unbelievably helpful! I’m headed off to your PayPal account when I’m done submitting this comment!
David
March 11th, 2009 at 3:45 pm
hey Denise,
I think I understand that you’re putting the main working logic for the functions directly into the jQuery object and then only making the build, update and serialize functions accessible via jQuery’s inheritance, correct?
So I’m a little unclear on what is happening when you reference “this” in the scope of jQuery.tableDnD.build or jQuery.tableDnD.updateTables. Specifically, when you’re calling “this.each” in one of those functions, what does “this” refer to?
Thanks!
March 16th, 2009 at 12:13 pm
Hi
All things work cool in this plugin. But I want to delete a row in the table. And I want to add an effect from jQuery when I do so.
I normally use divs to create my table layouts. For I am unable to add effects such as fadeOut etc.
Any suggestions???
March 18th, 2009 at 1:03 pm
Your Drag-n-Drop is very slick. Thank you! I tried a few sorting jquery routines but I couldn’t get them to work for me. This worked great right off the start.
I do have one problem I could use a tip on, if you would. I created a table of thumbnail images that a user can drag-n-drop for sorting them – one image per row. I send the serialized data to a second script for db processing to set the sort order. That all works. Problem: I cannot click on the images to drag-n-drop them. I had to add a td cell next to the images and can use that to drag on. I can click on the text in the td cell to move the rows, but I cannot click on the images td cell. Any thoughts on how to make the images td cell drag-able?
I cannot post the url to this sorting page as it is in a protected site (admin section).
March 23rd, 2009 at 10:01 pm
I am using the Table Drag and Drop plugin within an ASP.NET Master Page website. I have been able to get the drag and drop capability to work fine, passing the serialized data back to the server via ASP.NET AJAX PageMethod call. However, I am hoping that I can get the raw HTML row information passed back via an ASP.NET AJAX PageMethod call as well. I have a checkbox, text box and drop down list control within my rows. Is it possible to use the row or rows[i] collection to achieve this?
Here is my jQuery:
jQuery(document).ready(function() { jQuery('# tr:odd').addClass('gridrow'); jQuery('# tr:even').addClass('gridrowalternate'); // Initialize the use of drag and drop jQuery('#').tableDnD({ onDrop: function(table, row) { var rows = table.tBodies[0].rows; for (var i=0; i<rows.length; i++) { jQuery(rows[i]).removeClass('gridrow gridrowalternate tDnD_whileDrag'); } jQuery('# tr:odd').addClass('gridrow'); jQuery('# tr:even').addClass('gridrowalternate'); PageMethods.UpdateSortOrder(jQuery.tableDnD.serialize()); } }); });I am using the ClientID syntax to deal with the ASP.NET Master Page name mangling issue. The PageMethods.UpdateSortOrder method call works fine and allows me to process the row order after a drag and drop operation. However, when I try to use the row or rows[i] data in a call to a PageMethod, the script just runs and runs; IE eventually tells me that the script is running for a long time and that I should stop in order to not make my computer unresponsive. Is there a restriction on the type of data that can be sent via an ASP.NET AJAX PageMethod call?
Thanks.
Karl
April 3rd, 2009 at 2:40 pm
you have done great research on this topic. i didn’t know many things about it. as really helpful. reading short information is always awesome rather than reading insanely huge books!
I didn’t understand nookat people, both sides
April 7th, 2009 at 1:31 pm
Hi!
How can I block the table with the event, uses tableDnD?
April 7th, 2009 at 2:06 pm
how can i save the order of the dragged table?
sorry am new to this but when i look at the source the table always starts with tr 1 sequently even after sorting?
April 9th, 2009 at 7:36 am
Has anybody found a solution/hack to drag multiple rows at once (e.g. selecting them using checkboxes)? It would be a really cool feature for an upcoming version.
Thanks
April 10th, 2009 at 3:46 am
doesnt seem to work in internet explorer 7
April 10th, 2009 at 11:29 pm
Karl,
Did you ever get your situation figured out? I’m trying to do something similar.
Thanks,
-s
April 16th, 2009 at 3:59 pm
Hi,
Is there someone who could help me with my problem.
I’am retrieving data from mysql and it’s getting around 170 rows at the moment (it’s a list of contacts) and i have setup script to save the new order back to database. The Drag&Drop is working perfectly on ie7, ie8 and firefox3.
It work’s on ie6 when i LIMIT the retrieved rows around 100-102 but at 104+ it fails when i drag and drop a contact to a new place. Any idea what’s causing the error and is there way to fix it?.
I have tested it on my own Windows XP SP3 + IE6 and friends XP SP3 + IE6 computers.
Don’t know if this helps but the error in ie6 is
line: 20
char: 27021
error: unspecified error
code: 0
April 18th, 2009 at 4:18 pm
Hello. This plugin is really nice. But there is one missing. From another table to use in my project should I do drag. You are a small sample may wonder? I’ll drag a table to another and record database.
April 20th, 2009 at 9:42 am
A small typo here:
$(#debugArea).html(debugStr);//no quotes
must be:
$(‘#debugArea’).html(debugStr);
April 28th, 2009 at 5:05 pm
Coming to this discussion late, but my question is whether anyone has a unified solution that can drag and drop stuff whether it’s rows in a table, div’s in a div, li’s in a list, a gallery of table cells with one record per cell, etc.
My framework allows data to be displayed in all these ways, but I’d like to be able to reorder things no matter what format the app is in.
Do I have to have a separate set of functions for all of em?
Thanks
Bagus
April 29th, 2009 at 7:58 am
Sweet! It worked right away! I though i had to convert my table into a list to sort it, but it just worked..
April 30th, 2009 at 4:00 pm
Hi,
I’m trying the plugin, but I have a problem. I need to pass the new order to a PHP script via ajax using this code:
$(document).ready(function() { $('#my_table').tableDnD({ onDrop: function(table, row){ $.ajax({ type: "POST", url: "write.php", data: "data="+ $.tableDnD.serialize() }) } }); });——————————
The PHP code just make a check of the $_POST['data'], and then I want to write to a file. Something like this:
if (isset($_POST['data'])){ $stringData = "okay\n"; $stringData .= $_POST['data']; }else{ $stringData = "no\n"; } @fwrite($fh, $stringData);The script write just the first line of the table! Can anyone please help me?
P.S.: I tryed to de-serialize using explode(“&”, $_REQUEST["data"]); or explode(“&”, $_POST["data"]); but without results…
May 12th, 2009 at 3:19 pm
I’ve been having trouble with this for hours…can anyone tell me why this code snippet isn’t working? The error is that TableDnD() isn’t a function….I’m sure I have the js files in the right spot….many thanks from a frustrated developer!
$("#mytable").tableDnD is not a function <html> <head> <script type="text/javascript" src="jquery-1.2.3.min.js"></script> <script type="text/javascript" src="tablednd.js"></script> <script type="text/javascript"> $(document).ready( function(){ $("#mytable").tableDnD(); }); </script> </head> <body> <table id="mytable" cellspacing="0" cellpadding="2"> <tr id="1"><td>1</td><td>One</td><td>some text</td></tr> <tr id="2"><td>2</td><td>Two</td><td>some text</td></tr> <tr id="3"><td>3</td><td>Three</td><td>some text</td></tr> <tr id="4"><td>4</td><td>Four</td><td>some text</td></tr> <tr id="5"><td>5</td><td>Five</td><td>some text</td></tr> <tr id="6"><td>6</td><td>Six</td><td>some text</td></tr> </table> </body> </html>May 12th, 2009 at 5:51 pm
I figured it out (see previous post)…somehow, I got a copy of tablednd.js and not jquery.tablednd.js (which you have to use with jquery.js to work)….I’ve since found “jquery.tablednd_0_5.js” that works with “jquery-1.3.2.min.js”
Whew! That was an adventure! Not sure where I went wrong earlier, but its working great now!!
May 21st, 2009 at 1:57 pm
I use your plugin (which works perfectly btw!), but now I have a problem.
I have a button, allowing me to add more rows to the table, and the newly added rows isn’t sortable anymore. How can I make them sortable?
May 21st, 2009 at 5:05 pm
Hi Ronny-André,
If you add rows, you need to re-initialize the dragging and dropping to add event handlers to the new rows. You can do this by calling
$("#myTableId").tableDnDUpdate().This should set everything up so that you can drag and drop the new row.
May 22nd, 2009 at 8:31 pm
Thank you for the great work. When row tracking (highlight row when hovering) is enabled the hover highlight and dragging highlight seem to display on multiple rows at the same time. This is ugly and momentarily confusing. As a work around I use the onDragStart/onDrop events to add/remove a css class “.table-dragging” to the entire table, then I use “.table-dragging .ui-state-hover { background-color: transparent !important; }” to cancel out the highlight. Perhaps you might consider including a cleaner workaround in a future version (unless of course I’m missing something
Otherwise, thanks again for this excellent plugin!
May 23rd, 2009 at 11:41 pm
Facing trouble using tableDnD AND tablesorter in the same table. When I drag one of my row, and then try to sort my table (with tablesorter plugin), the whole table is duplicated once. here is what it does :
step 1 :
#1 | row 1
#2 | row 2
#3 | row 3
step 2 : dragging a row using tableDnD
#1 | row 1
#3 | row 3
#2 | row 2
step 3 : sorting the table, using tablesorter
#1 | row 1
#3 | row 3
#2 | row 2
#1 | row 1
#2 | row 2
#3 | row 3
How can I solve that ?
May 27th, 2009 at 2:47 pm
[...] table drag and drop jquery plugin [...]
May 28th, 2009 at 6:35 am
Sample for PHP reorder:
javascript:
<script type="text/javascript">
$(document).ready(function() {
$("#tbladdpage tr:even").addClass("alt");
$("#tbladdpage").tableDnD({
onDragClass: "myDragClass",
onDrop: function(table, row) {
$.ajax({
type: "GET",
url: "reorderpage.php",
data: $.tableDnD.serialize()
});
},
dragHandle: "dragHandle"
});
$("#tbladdpage tr").hover(
function() { $(this.cells[0]).addClass("showDragHandle"); },
function() { $(this.cells[0]).removeClass("showDragHandle"); }
);
}
);
</script>
table:
<table id="tbladdpage" border="0" cellpadding="2" cellspacing="2"
width="100%">
<tbody>
<tr id="26"><td class="dragHandle"> </td><td align="center">1</td><td>Data
1</td></tr>
<tr id="27"><td class="dragHandle"> </td><td align="center">2</td><td>Data
2</td></tr>
<tr id="28"><td class="dragHandle"> </td><td align="center">3</td><td>Data
3</td></tr>
<tr id="30"><td class="dragHandle"> </td><td align="center">4</td><td>Data
4</td></tr>
<tr id="23"><td class="dragHandle"> </td><td align="center">5</td><td>Data
4</td></tr>
</tbody>
</table>
php script reorderpage :
foreach($_GET["tbladdpage"] as $key=>$value) {
$query = "UPDATE site_content SET
position=".$key." WHERE id=".$value;
mysql_query($query);
}
CSS:
.alt {
background: #f5f5f5;
}
.dragHandle {
width:80px;
}
.showDragHandle {
cursor: move;
}
.myDragClass {
background-color:#d5d5d5;
-moz-border-radius: 5px;
}
May 29th, 2009 at 4:16 pm
Ciro,
If you’re running into the same problem I was then you need to escape the table serialize output before you can send it via ajax. For example this is the data my php script was getting before with the code you posted:
“trigger_logic[]=”
After escaping the serialized data:
data: “data=” + escape($.tableDnD.serialize())
The data the php script received was correct:
trigger_logic[]=&trigger_logic[]=2&trigger_logic[]=1
May 30th, 2009 at 12:44 pm
Hi,
I have tried making it work in my Ruby on Rails application but I couldn’t.
I have placed
in application layout file.
Have content_for :head on the page having desired table.
$(document).ready(function() {
$(“#table-1″).tableDnD();
});
have placed the sort method in the controller as well. But it is not working
What else is that I am missing here to have it working !? Please help someone
June 1st, 2009 at 8:40 am
FAQ: My call to tableDnD() doesn’t work!
Answer: If it doesn’t work, it’s probably because you haven’t got the tableDnD code working properly. It won’t matter whether you’re using Ruby on Rails, Java, Groovy, ASP, PHP or whatever on the server as this is client-side javascript.
So next, try these in order:
$(document).ready(function() {...}then insertalert("This works!"). You should see the alert as soon as the page is loaded. If you don’t it’s because the core jQuery code isn’t being loaded correctly, or you’ve got one of the other problems above, or that your javascript is malformed in some other way. Try adding alerts before and after the call to tableDnD(). If the first works but not the second, then it’s probably because the tableDnD code isn’t being loaded properly. If both alerts work, try the next things on this list.$('#table-1 tr:even').css('background', '#ecf6fc');(with your table ID instead of table-1, but keeping thetr:even). This should give you alternating background stripes to your table. If it doesn’t it means that either JQuery itself is not loaded properly, or that the ID of the table isn’t unique or you’ve got a typo. If you do get the stripes, but you don’t get the drag and drop, then it means that the tableDnD code isn’t working, so check that the script is loaded correctly.Hope this helps.
June 1st, 2009 at 11:07 am
Hello,
I would like to use the third demo but I don’t know which scripts I have to include?
and where do I have to include the ajaxTest.php?? ->http://www.isocra.com/articles/ajaxTest_php.html
June 3rd, 2009 at 11:57 pm
Does anybody know how to get this to work with ‘rowspan’? I have a row that has a large cell that spans 2 rows followed by two rows, similar to how most email programs display an email icon, then the subject followed by a preview of the email right below that. TableDnD treats the ‘preview’ as a separate row (because it is). So when I drag either the Subject row or the Preview row they do not move together.
Hope this works. This is a row in a table made up of 2 rows, and 2 columns.
I want to be able to drag the 2 spanned rows as a single row. Maybe I can’t do it using ‘rowspan’ but does anybody know of another way to split a cell into two rows like this?
June 4th, 2009 at 12:04 am
Also, this script seems to only work on TD elements, not TH. In my example above, I wanted the ‘Icon’ and ‘Subject’ cells to be styled as TH while the “Preview’ cell styled as TD and be able to drag using any portion of the row. It doesn’t work; am I missing something or is that by design?
June 4th, 2009 at 8:40 pm
One thought I had to solve my first problem was for TableDnD to move all rows with the same ID when one of the rows is dragged. I have no idea how to do that, but I will work on it. It’s been suggested here before, but nobody’s really taken up the task of working it out.
In regards to my second problem, I fixed it by adding || (ev.target.tagName == “TH”) to the row that contains (ev.target.tagName == “TD”).
June 5th, 2009 at 7:30 am
HI Itlan,
It’s pretty difficult to move the rows if you use rowspan because the DOM becomes very complicated. One alternative would be to have just a single row and then use different formatting for your subject and preview. This might make more semantic sense anyway, for example if you have a table of movies, then you have one row per movie, the first column has an icon which is a link to the trailer, the second column has something like <h3 class="title">Movie title</h3><div class="description">Movie description</div>.
Thanks for the fix to the second problem re dragging header rows. I will look at allowing headers to be optionally draggable in the next version.
June 5th, 2009 at 8:29 pm
Hi DenisH, Cameron (December 12th, 2008) worked out a way to move 2 rows, but the problem (as he stated) is that you are able to move a row to the space between the 2 rows (i.e. between the Title and Description). I was able to get it to work pretty good in the UP direction by making the second row NODROP. The DOWN direction still has the same problem though. Still working on it, but I will use your idea of a DIV for the description, thanks for the great plugin!
June 7th, 2009 at 3:03 am
Hello, I would very much like to see pagination added. I am using the jquery pagination plugin but I can’t think of a good way to drag rows to other pages. It would be great if I could do this without having to have all the pages loaded at once. Currently I load each page with ajax and combo tablednd with livequery.
June 9th, 2009 at 4:47 pm
Hey, wanted to say 2 things –
#1 – I am a huge fan of your jquery plugin for table drag and drop
#2 – I seem to be having an issue – when I go to drag a cell and mouseover text the browser winds up copying the text rather than dragging the row. There is no issue when I place the mouse elsewhere outside of the row (off the text). This behavior does not happen on your site but does on mine. Have you seen this and do you know how to resolve it? Anybody? Thanks!
site locations: http://www.congruencewebdev.com/table_dnd.php
June 9th, 2009 at 5:11 pm
I just figured it out – its related to the tag I used to make it easier to do dynamic updates/ ajax. I’d hide the and create a new input when the edit button is clicked. It’s easy to fix, I just need to do things differently. Not sure if this is worth addressing or fixing, but it might be a good idea to put it on your site for reference. I’ll just remove the span tag and then when edit is clicked use the remove() function in jquery, then swap it back when its saved. Awesome plugin, much love to Isocra.
June 18th, 2009 at 1:25 am
This is a very useful plugin, but I wish there was an option (if not the default) to only make tr’s within a tbody dragable and droppable. Very rarely would you ever want to drag rows in a thead or tfoot section, and in that case, then I would say it’s better to apply an explicit css class to *enable* these functions, instead of always requiring the “nodrop nodrag” classes to disable them.
June 20th, 2009 at 6:54 pm
Hi there,
I recently installed and activated the great AJAXed WordPress plugin. I’m testing it out and I noticed that when I enable effects, the fade-in for newly added comments only works on the first comment. Additional comments exhibit the “abrupt transition when new content is loaded” mentioned on the effects page.
Is anyone else experiencing this issue, and does anyone know of a fix for it?
June 21st, 2009 at 11:39 am
[...] 3. Table Drag and Drop JQuery plugin [...]
June 24th, 2009 at 4:20 pm
If you are haveing problems with serilising tables and getting a difference between IE7 and Firefox, check to see if you are using THEAD and TBODY tags. Or you are just using a top row for TH tags. If so IE will return the first Item in the array as index 0 blank. But firefox will return as you expect.
To solve just adjust you jQuery Selector to identifiy the TBODY area not just the Table. ie
instead of: $(‘#theTable’).tableDnD(
use: $(‘#theTable tbody’).tableDnD(
June 29th, 2009 at 11:34 am
I’m not sure if this behavior is wanted or a bug, but if u specifiy a dragHandle, the onDragStart event gives the matching cell (td tag) as the row parameter and not as i supposed the row (tr tag). Found a simple bugfix for that by changing line 135:
config.onDragStart(table, this);
to
config.onDragStart(table, this.parentNode);
June 29th, 2009 at 2:34 pm
I’ve been successfully using tableDnD in jQuery 1.2.3 with the live query plugin, however I have moved to jQuery 1.3.2 and had to namespace my javascript functions this has caused my tableDnD to fail as it is no longer found. Anyone know how to get round this? Sorry if the answer is obvious.
July 1st, 2009 at 10:11 am
I have a small problem with this drag’n'drop. When ever I lock a element it is not lock into place, but moves up or down when I place other elements under or above it.
Can it be done so if I lock element 3 it stay on spot 3 and don’t move down to place 4 if I move a other element above it ??
July 2nd, 2009 at 3:00 pm
Hi, I got the script working by adding a ; after the } before jQuery.fn.extend(
However I also had to copy the contents of the file and paste it to be inside the namespace rather than using a script include tag. Any ideas why?
July 2nd, 2009 at 5:17 pm
Hi
for a project at work, I needed to create a way to drag and drop rows and columns
thanks to this plugin, moving the rows went fine.
moving the columns however was tougher to find a way to do.
at the moment its somewhat crude and buggy, but using this plugin as a place to work from, I created a way to drag and drop columns, I hope that is alright, here’s an example of it
would you like the code now or once it is more refined?
-max
July 2nd, 2009 at 5:17 pm
http://users.wfu.edu/strumc7/DragNDrop/
sorry about the double post
July 2nd, 2009 at 5:53 pm
I am needing an table to input text drag’n drop.
I tried to adapt your example with no success.
Thanks
July 2nd, 2009 at 6:01 pm
Sorry to double post, but here is the info I needed about table to input drag
http://stackoverflow.com/questions/199651/jquery-any-row-picker
So, in case anyone needs, this may help
July 5th, 2009 at 2:32 am
Hi guys, I’m facing a major issue here:
when drag, you will use ajax to submit serialize data — data: $.tableDnD.serialize()
In my scenario
First, when I select from drop down onchange event it will show the table based on the drop down id.
It means the table is tied to the drop down id.
So when I on drag drop to update the row order, I also need to pass in the selected drop down id, in order for me to know what is the table to be updated.
How can I do that?
I try to $.tableDnD.serialize() + ‘|’ + dropdownselectedvalue
it just not working
July 5th, 2009 at 6:39 pm
Hi,
What do you want the data going back to the server to look like?
I would have thought you want to do $.tableDnD.serialize()+”&dropDownID=”+dropdownselectedvalue
That will give you a set of properties and values that you can GET or POST back to the server and the server will be be able to pick out the dropdown value easily.
July 8th, 2009 at 8:02 pm
Hi! Is there a way to select multiple rows and drag them all together?
July 9th, 2009 at 4:17 am
oh great, + “&dropDownID=” + works well.
Btw, have another challenging question. I am creating a table that will list down all the questions- start from 1 to 10.
The table format.
Question No | Question Title
1. how are you
2. what do you like
3. whats ur name
I want to be able rearrange the order of question title, BUT remain Question No column to be unsorted.
It means when you drag question title from row 1 to row 3, 1. won’t follow to row 3.
Reason: people can easily see what question is in what Question No.
Any way to work around?
July 9th, 2009 at 6:58 am
Two replies:
To “Developer”, I’m sorry there isn’t a built-in way to move multiple rows at the moment. You could implement something by having checkboxes or some other visual way for the user to multi-select rows and then in the onDrop method move the other rows yourself?
To “I need help”, the only way I can think to do this is again in the onDrop to renumber the questions. So the column does get sorted, but you renumber on drop. Visually this might work better for the user anyway because they can see that they’re moving question three to between questions 4 and 5 but then when they drop the row, all the questions get renumbered automatically.
July 9th, 2009 at 9:11 am
Hello,
i try to order a gridview via drag&drop. it works but i can’t save my changes. i think i must add an id in but i don’t know how.
Please help me.
July 10th, 2009 at 8:11 pm
Hey I found this last night and it was almost exactly what I wanted. And what it didn’t have I found easy to add, thanks for your work!
The first thing I did was to change the dragHandle to be a regular jQuery selector rather than forcing it to be a class name attached to a . The other thing I did was add a onDrag event which gets called every time the DOM position changes.
My changes are probably not the right way to do things, but they seem to work…
101a102
> onDrag: null,
126c127
var cells = jQuery(table.tableDnDConfig.dragHandle, table);
135c136
config.onDragStart(table, $(this).closest(‘tr’)[0]);
276a278,282
>
> if (config.onDrag) {
> config.onDrag(jQuery.tableDnD.currentTable,
> jQuery.tableDnD.dragObject.parentNode);
> }
Thanks again!
July 10th, 2009 at 8:13 pm
I guess my patch blew up upon posting, oh well.
July 13th, 2009 at 3:53 pm
This is a very useful plugin. Thanks! Is there a way to add the ability for keyboard users to move a row up or down? You have a start in the example showing the dragHandle. Adding the ability to move one up or down using the dragHandle would make the plugin more accessible. Any ideas on how this could be done?
July 15th, 2009 at 12:05 pm
Hi, first of all, this plugin is da BOMB. I managed to successfully implement dragHandle and onDragClass for asp.net GridView. However I have one small problem here. Based on the code below,
$("#GridView1").tableDnD({ onDrop: function(table, row) { alert(row.id); } });the “table” parameter is defined but the “row” parameter is always undefined. When I try to “alert(row.id)”, I get a blank messagebox. This could be a problem with the GridView. Could anyone help me with this?
July 15th, 2009 at 8:49 pm
First, thanks for the great plugin.
I have been using it quite successfully for a while. I now have a situation where I need to use strings as id’s. some of which have hyphens.
The serialize function seems to utilize the tableDnDConfig.serializeRegexp property which only uses the part of the id after a hyphen.
i.e. test-red becomes red after serialization. Several of my id’s have hyphens and this is throwing things off. My problem seems to be solved by setting serializeRegexp to null. I just was wondering why it was set up this way to be sure I wasnt inadvertantly screwing something up that I wasnt catching.
Thanks a lot.
July 15th, 2009 at 9:21 pm
Hi Duane, the serializeRegexp is for compatibility with other plugins that also have a serialize method and work in the same way. If you want to include hyphens, you can just change the serializeRegexp in the initial options. If you change it to something like /^.*$/ that should just return the whole thing (a good place to try regular expressions is this Online Regular Expression Tester). Hope that helps
July 15th, 2009 at 9:27 pm
Hi EastGuy,
Your code looks right to me, I can’t see why it doesn’t work. Have you tried using Firebug to debug and see what’s going on? If you spot something wrong, please post back.
Thanks
July 16th, 2009 at 3:08 am
Thanks Denis,
Thats what I though I just wanted to be sure I wasnt missing something.
July 17th, 2009 at 5:30 pm
It’s my mistake. I’m new to client-side scripting. I just found out I’ve to manually set the id during RowDataBound event and now it works!
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
TableCell cell = new TableCell();
if (e.Row.RowType == DataControlRowType.DataRow)
{
cell.CssClass = “dragHandle”;
cell.Style["cursor"] = “move”;
}
cell.Text = “ ”;
e.Row.Cells.AddAt(0, cell);
e.Row.ID = “row” + e.Row.RowIndex;
}
July 21st, 2009 at 10:02 am
Hi Denis,
Thanks for your plugin. It works great in my project. I have one clarification. I added confirmation before update the table. If user clicks Cancel How we can “Undo” the Move. Please advise me. Thanks
July 21st, 2009 at 10:13 am
Hi all,
Thanks for the script and it works fine for me. And now I need one more feature on it. Kindly help on this. Actually I have done the Drap and Drop the table row from one place to another and call the ajax page to do the updation.
Now before doing updation (that is before calling ajax page), we need to ask the confirmation from the user like “Are you sure?”. If user accepts then we can call the function. If user “Cancel” the operation, WE NEED TO HAVE THE ROW IN THE PREVIOUS POSITION… I don’t know how to do this.. Please help me on this…
July 21st, 2009 at 10:43 am
Hi Patrick and Karthik,
It looks like you both want the same thing which is to restore the table back to how it was before the drag.
The plugin currently moves the row as you drag it, so there’s no built-in way to restore it to its original position, but you could record it yourselves in an onDragStart method. In this method you are passed in the current cell, so if you call cell.parentNode, that will give you the current row, and if you call nextSibling on that, then that will give you the row after the current row. So store that away as, say, oldSlibling (if it’s null it means it’s the last row).
Then in the onDrop, if the user cancels, you can put the row back where it was using something like
droppedRow.parentNode.insertBefore(oldSibling, droppedRow);
You’ll need to deal with the case where it’s the last row (and therefore oldSibling is null).
Something like that should do the trick. Hope that helps.
July 22nd, 2009 at 6:11 am
[...] if they are able to change the order of invoice lines quickly. In my application I used jqGrid with TableDND extension. Here’s how I got it [...]
July 25th, 2009 at 5:44 pm
I know you got a ton of comments here, but I just wanted to thank you for this wonderful plugin. Works great right out of the box for me.
-Justin
August 3rd, 2009 at 1:28 pm
To disable header rows dragging just split the table into sections and and then apply this plugin only for the . Ex:
# —– HTML ——#
HeaderRow
First content row
Second content row
# —– JS ——#
$(‘#draggable-table > tbody’).tableDnD();
August 3rd, 2009 at 8:41 pm
What’s the easiest way to call a reorder ASP .NET method?
August 4th, 2009 at 3:44 pm
Great resource.. Thanks for posting it!
One small contribution… Since we’re only moving rows (vertical movement) the cursor could be switched to ‘ns-resize’ instead of ‘move’.
item.style.cursor = “ns-resize”;
August 13th, 2009 at 10:23 pm
Was curious as to what you would call if you add a new row so as to make it draggable post loading of the dom.
Solid plugin btw.
August 14th, 2009 at 12:26 pm
Hi,
First of all lots of thanks for the plugin. I got an issue with Drag N Drop, actually i have placed the drag n drop table inside a div and after each drag n drop the div content will update. I am updating the div with same table id and other things but it wont work after the div updation.Please help me to get out of this issue.
Here is my client side code
$('#table-1').tableDnD({ onDrop: function(table, row) { var reorder_ids= $.tableDnD.serialize(); jConfirm('Are you sure you want to reorder?', '', function(msg) { if(msg) { // save insurance preference on reorder var pars = ""; var url = "server.php"; var content = $.ajax({ url: url, type: 'POST', data: pars, async: false }).responseText; //$('#div_idt').html(content); // updating div containing drag n drop table $('#table-1').tableDnDUpdate(); // update table after drag n drop // end save insurance preference on reorder } }); // end jConfirm } // end onDrop }); // end tableDnDSeptember 1st, 2009 at 5:28 pm
works great for me! Thanks for plug-in
@Eastguy try using row.rowIndex instead of row.id
September 2nd, 2009 at 12:58 pm
[...] row) { 21 $(#debugArea).html("Started dragging row "+row.id); 22 } 23 }); 24}); 25 Demo: http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/Download: http://www.isocra.com/articles/jquery.tablednd_0_5.js.zipSource: [...]
September 6th, 2009 at 1:25 pm
[...] 14. Table Drag and Drop jQuery plugin [...]
September 6th, 2009 at 4:12 pm
[...] ColumnManager plugin jQuery treeTable CSV2Table Table Pagination jQuery TableRowCheckboxToggle Table Drag and Drop jQuery plugin uiTableEdit [...]
September 7th, 2009 at 12:15 am
The plugin’s great – thanks so much for it. I’m having an implementation issue, though. I’ve created a test page that works perfectly, but when I move code and css into the working file (which has various unrelated css and js files), drag-and-drop functions work, but dragging causes highlighting of table cell contents under the crossing cursor (ordinary highlighting, that is – as if you dragged over text to highlight in order to copy it, for example).
The tablednd table is necessarily nested within another div tag, so some sort of DOM conflict seems likely. Can anyone suggest a way to track down/repair the issue?
Thanks!
September 7th, 2009 at 10:20 am
[...] Table Drag and Drop jQuery plugin [...]
September 7th, 2009 at 8:21 pm
I figured out my problem – basically, I modified the code to use grab/grabbing cursor in a syntactically sketchy way that broke in a more complex DOM structure. I’ll fix it and post revisions for the grab/grabbing cursor.
September 15th, 2009 at 1:28 am
I’m attempting to add some rows and then use tableDnDUpdate(), but I’m not sure why it’s not working.
The original rows are still draggable, but the newly created row is not. Here’s what I’m trying:
$(document).ready(function() {
// Initialise the table
$(“#table-1″).tableDnD();
});
function insertRow() {
var newRow = document.createElement(‘tr’);
newRow.innerHTML = ‘new row’
$(“#1″).after(newRow);
$(“#table-1″).tableDnDUpdate();
}
1
2
3
4
5
6
September 15th, 2009 at 1:29 am
I’m attempting to add some rows and then use tableDnDUpdate(), but I’m not sure why it’s not working.
The original rows are still draggable, but the newly created row is not. Here’s what I’m trying:
$(document).ready(function() { // Initialise the table $("#table-1").tableDnD(); }); function insertRow() { var newRow = document.createElement('tr'); newRow.innerHTML = 'new row' $("#1").after(newRow); $("#table-1").tableDnDUpdate(); } 1 2 3 4 5 6September 15th, 2009 at 7:42 pm
Thanks for the plugin!
I ran into an issue: if I run tableDnD(), then change which rows have “nodrag” and then run tableDnDUpdate(), any row that was draggable is still draggable, even if it now has the “nodrag” class.
Fix here: http://gist.github.com/187561
September 16th, 2009 at 6:43 pm
Nice script. Its too bad Jquery doesn’t support sorting like list elements but this is a great tool nonetheless.
September 17th, 2009 at 4:13 am
Thanks for the plugin. Sorry to ask a dumb question, but I’m a dumb guy. I’d like to renumber items on the onDrop event so that rows are renumbered chronologically. Seems likely this could be fairly easily accomplished if the proper jQuery syntax and DOM conventions are known. Can someone clue me in? Using jQuery, how would you access and and write new values to a particular cell/column in a table?
Thanks!
September 18th, 2009 at 4:49 pm
Hi, Denis, great work!
I’m trying to simplify my code by excluding the header row as suggested by Steve by specifying the TBODY element in my table: $(“#items tbody”).tableDnD({ … });
When I serialize the new sort order, I get only brackets, not the table name and brackets; instead of
items[]=&items[]=2&items[]=5&items[]=1
I now get
[]=2&[]=5&[]=1
The good news is I no longer have to discard the first element (the header row) that appears in the first example. The bad news is that my array keys are now just brackets, reducing the clarity of my code.
I’m looking for a way to name the array elements. In the source code (I’m using version 0.5) I see
serializeParamName: null, // If you want to specify another parameter name instead of the table ID
but this option doesn’t appear anywhere else in the source.
I’m not sure from the comment exactly what this should do; I *think* it would let me specify the name of the keys in the serialized array, like
serializeParamName: ‘foo’,
…
foo[]=2&foo[]=5&foo[]=1
Is that the intent? And, is this implemented in any version of the code? Right now, it looks like a dead option…
( I’m also not clear why the serializer generates the brackets to begin with; it would be clearer to get
items=&items=2&items=5&items=1
What are the brackets for? )
September 18th, 2009 at 5:46 pm
Stuckey,
What do you mean by “rows are renumbered chronologically”? Can you give a before-and-after example?
In general, to select a specific row and cell in a table with id=foo, the jQuery syntax can be something like
$( ‘#foo tr:eq(i) td:eq(j)’ )
where i and j are the zero-based indices to the desired elements. To select the 3rd cell in the 2nd row, that would be
$( ‘#foo tr:eq(1) td:eq(2)’ )
and to set the value, use .val( bar ) wher bar contains the new value. Putting it all together:
var i = 1, j = 2, bar = ‘quux’;
$( ‘#foo tr:eq(1) td:eq(2)’ ).val( bar );
3rd cell, 2nd row of table ‘foo’ now holds the value ‘quux’
If you want to set the nth element of ALL rows at once, look at the :nth-child() selector, which lets you do e.g.
$( ‘#foo tr:nth-child(3)’ ).val( bar );
which sets the 3rd cell on ALL rows in the ‘foo’ table to the value of bar. Note that nth-child(n) takes a 1-based index, but :eq(n) takes a zero-based index.
Show an example of how you’d like the chronologically-numbered table to look and we’ll try to give you specific code to do that.
September 18th, 2009 at 5:46 pm
oops, the example should be:
var i = 1, j = 2, bar = ‘quux’;
$( ‘#foo tr:eq(i) td:eq(j)’ ).val( bar );
September 21st, 2009 at 8:51 am
Val, thanks for the reply and information. Apologies for the late reply.
I misused “chronologically.” I meant to refer to a numerical reordering of numbers in a column. To clarify my intentions, I want to adjust numbers displayed in the left-most column of my table after dragging/dropping rows. To illustrate, if my initial table HTML is this:
1. A Man Called Horse
2. The Good, The Bad, and the Ugly
rendering this (roughly):
1. A Man Called Horse
2. The Good, The Bad, and the Ugly
if a user drags and drops to reverse the order, I’d like to reorder the numbers in the left column numerically, like so:
1. The Good, The Bad, and the Ugly
2. A Man Called Horse
Thanks again for the reply. I’ll see if I can work out a solution with the code you provided.
September 21st, 2009 at 9:06 am
Oops – the first table was meant to describe the html explicitly – instead the marks were stripped, resulting in redundancy. Sorry for confusion. For what it’s worth, I meant to show the html for the table as follows:
<table>
<tr>
<td>1.</td> <td>A Man Called Horse</td>
<td>2.</td> <td>The Good, The Bad, and the Ugly></td>
<tr>
</table>
September 21st, 2009 at 12:29 pm
Stuckey: you could define an ondrop callback that does something like: $(“#foo tr”).each(function(index) { $(this).find(“.number”).html(index+1); });
September 23rd, 2009 at 10:19 am
[...] Table Drag and Drop jQuery plugin [...]
September 26th, 2009 at 12:04 am
[...] sitio de Table Drag and Drop jQuery plugin» [...]
October 2nd, 2009 at 9:30 am
In the second preview there is a little mistake.
This next is from:
// Make a nice striped effect on the table
$(“#table-2 tr:even’).addClass(‘alt’)”);
And has to been:
// Make a nice striped effect on the table
$(“#table-2 tr:even”).addClass(“alt”);
October 2nd, 2009 at 7:39 pm
Hi,
I have a problem.
I have multiple DnD’s on a page, and dont really know what the best way of getting them into a form is. At the moment i cant get it in a form in any way :S
this is how im trying to do it now:
$(“div.container dl dd table”).tableDnD({
“onDragClass” : “slepen”,
onDrop: function(table, row) {
$(this).next(‘input’).val($.tableDnD.serialize());
}
});
with an field right after the table.. but also this.className doesnt seem to work…
the big issue is the fact that er could be multible and variable names for the DnD, so i can maken 1 script for several DnD’s, but need to make it dynamic.. how to do?
October 3rd, 2009 at 12:44 am
Did anyone ever manage to get sub-levels supported?
October 4th, 2009 at 10:22 pm
[...] Haz clic aquí para ingresar al sitio de Table Drag and Drop jQuery plugin» [...]
October 5th, 2009 at 12:41 pm
[...] jQuery Table Drag and Drop (tablednd) [...]
October 6th, 2009 at 2:38 pm
I’m using this with the jQuery Grid and found that using DnD prevent selecting a row or double clicking on a row. I modified TableDnD to keep track of whether or not it’s actually dragging by implementing a dragThreshold and comparing the mouse move coords to the mousedown coords.
I’ve only partially tested this with jQuery grid. Now, click and double click still fire and DnD works though it still fires a drag drop event when not actually dragging.
Here’s the code:
October 7th, 2009 at 10:00 am
Hi,
I am sorry to waste your time but…I need help.
I am not so familiar with jQuery and AJAX, but this drag and drop function is exactly what I need. Drag and Drop works already really fine but I have to change the order in the database. The last ten hours I spent with reading a lot of AJAX examples, source codes and AJAX tutorials, but nothing does really work or meet my requirements. Unfortunately I even do not really understand what I am doing.
I have a table, dynamically filled out of the database table “mittagstisch” (by using PHP), sorted by field “mt_rf”. Where do I have to add which code to change the value of “mt_rf” in the database after dropping. Where do I have to adjust what to solve my problem.
Thank you very much for your help.
October 9th, 2009 at 6:37 pm
why is not working with jquery 1.3.2? is there any updates? can i download it.. or i can just fixed it thanks..
October 12th, 2009 at 2:30 am
For don’t move the normal rows over table header (table>tr>th), chage this code (line 311):
var nodrop = jQuery(row).hasClass(“nodrop”);
if (! nodrop) {
return row;
} else {
return null;
}
for this code:
var nodrop = jQuery(row).hasClass(“nodrop”);
if (! nodrop && jQuery(row).children(0).get(0).tagName != ‘TH’) { // this line is changed
return row;
} else {
return null;
}
The pluggin is excellent, thanks!
October 21st, 2009 at 9:19 am
Thank you so much, a really useful plugin. I’ve searched for solution like this for a long time, but lots of JQuery sites gave me nothing interesting.
October 22nd, 2009 at 4:47 pm
this is fun
October 26th, 2009 at 11:03 am
[...] Table Drag and Drop JQuery plugin [...]
October 27th, 2009 at 7:47 am
Hi,
Thank for very useful code.
However, I think there is bug here. I added two line of text in TD. From the second line of that TD, I tried to drag and drop it to the next line. Sometimes it didn’t work.
Hope you can find the solution for this case.
October 30th, 2009 at 12:38 pm
Hi,
really it’s just the code what i m looking for.But i have two inquery
1. Can i set both nodrag and nodrop on a row?Because i don’t want to show DRAG image on such row.
2. Row added using javascript has no refence in tableDnD.How can i get it?
November 2nd, 2009 at 8:08 am
[...] Table Drag and Drop JQuery plugin – použití TableDnD pluginu [...]
November 4th, 2009 at 8:21 pm
[...] optimize browser rendering. I already knew that having a lot of CSS classes could be an issue. The Table Drag and Drop jQuery plugin was also a potential problem because it runs something on the table just before the content of the [...]
November 6th, 2009 at 8:38 pm
[...] im zweiten Test neben den genannten großen Bliotheken auch noch kleinere Plugins (jQuery Cookie, Table Drag’n'Drop) enthalten waren, deren Code noch nicht optimiert [...]
November 10th, 2009 at 11:06 am
[...] TableDnD jQuery plugin allows the user to reorder rows within a table, for example if they represent an ordered [...]
November 10th, 2009 at 11:13 am
I made a short post about how to make a better usability for the users if you use the TableDND plugin. Mimic a “ghosting” like behavior and drop back the moved row if the user cancel the movement. You can read it here: http://www.eldanor.hu/improving-tablednd-usability
I hope it will save time to everybody who try to setup her/his TableDND.
November 10th, 2009 at 3:15 pm
I have a gridview (data populated servers side) and am using the TableDnD jQuery to reorder rows. However, it errors in html with “Microsoft JScript runtime error: Object expected” at:
$(document).ready(function() {
$(“#GridView2″).tableDnD();
});
I do have the following installed and referenced:
Am I missing something??
November 10th, 2009 at 3:16 pm
I am using:
jquery-1.3.2.min.js
jquery.tablednd_0_5.js
November 12th, 2009 at 6:42 pm
has anyone implemented or will it be implemented in the future for sub levels / sub items?
November 19th, 2009 at 4:23 pm
I can update MYSQL DB :S
Any GooD Example … ?
November 19th, 2009 at 4:24 pm
sorry, i say “I CAN´T”
November 23rd, 2009 at 3:11 pm
[...] Table Drag and Drop [...]
November 24th, 2009 at 6:03 am
[...] Table Drag and Drop [...]
November 28th, 2009 at 3:22 am
Just offering a heads up to anyone trying to use UUID’s as TD ID values. Make sure you set the serializeRegexp value when calling tableDnD, as per the following:
$(‘#table’).tableDnD({
serializeRegexp: /^.*$/
});
November 29th, 2009 at 12:45 am
Thanks for this, it’s a pretty great plugin. I made one tiny addition which I thought you should incorporate back into the release.
I have a table where every other row is dark. While dragging the rows, I need to update the classes on the fly otherwise the table looks broken because there might be two dark rows together.
I added an “onDrag” variable to the config right under onDragStart (line 102). Then in the mousemove function on line 279, I added: if (config.onDrag){ config.onDrag(); }
Hope this helps!
December 1st, 2009 at 1:34 am
Thanks this thing is really cool
I noticed load of people on here looking to drag and drop multiple rows anyone had any luck with that?
anyone working on it? I have a project where it would meet my spec perfectly if i had this ability.
otherwise anyone seen a tree with drag and drop reordering that has full html nodes not just text and an image?
Thanks again
December 1st, 2009 at 9:20 am
Is there any possibility to integrate this fine plugin into TinyMCE ? This would be great for me…
December 4th, 2009 at 12:16 pm
Hi, nice plugin.
Just wanted to say that the function onDragStart(table, row) actually returns the table cell instead of the table row for me. The documentation above says it should return the row.
Also, you say that the plugin generates a javascript error when you drag beyond the bounds of a tbody. For me, not being able to drag outside of a tbody turned out to be a feature, very useful to constrain the range. The error message can easily be suppressed by enclosing line 273 and line 275 in try catch blocks. This won’t break the functionality at all.
December 4th, 2009 at 3:36 pm
Hi I am trying to drag and drop with dynamically added rows.. but does not work. The static rows can be dragged but the newly added row is not draggable. Means cannot pick the new row and move.. where as the static rows can be moved even in place of the new row.
Any suggestion.
Actually I am creating a table dynamically and wants all the rows to be draggable before saving.
December 8th, 2009 at 1:56 pm
Does this plugin support nested lists? Or sub-lists as someone else called it.
December 9th, 2009 at 2:03 am
Regarding onAllowDrop implementation.
I need parse both parameters in the function passed by onAllowDrop
So (Pau talk about it above) I changed:
(line 269 –not line 301– @ version 0.5)
var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
by:
var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj[0], y);
In this way I can do something like:
function myAllowDrop(draggedRow, myrow) {
var mycel = draggedRow.getElementsByTagName(“td”)[0];
if (mycel.innerHTML != “ ”)
{
var mycel = myrow.getElementsByTagName(“td”)[0];
if (mycel.innerHTML != “ ”)
return true;
}
}
Thanks Denis for your work…
December 14th, 2009 at 5:26 pm
Hi,
I need to implement a drag and drop functionality in web. The situation is, I need to drag content from a popup window and drop it into the parent window. Is that really possible? Please let me know.
Thanks in Advance
December 14th, 2009 at 8:05 pm
Hi. Just wanted to ask about progress implementing dragging between tables…
December 24th, 2009 at 7:25 am
[...] Table Drag and Drop [...]
January 5th, 2010 at 10:52 am
Can any one help me with this plug ins
http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/
In this plug ins user can drag and drop only one row, my need is to drag and drop Multiple row.
Thanks
Nilesh J. Macwan
January 5th, 2010 at 3:13 pm
Thank you! Very good script!
January 9th, 2010 at 2:27 pm
The (X)HTML-standard indicates that the ID-attribute cannot start with a number which seems to be the key requirement for this plugin to work. Please tell me I’m wrong?
January 10th, 2010 at 11:53 pm
It doesn’t have to start with a number. I think some of the examples used above do start with a number, but others do not. For example, table5-row-4 is the format for one set of ids in the examples above.
It is nice to have some kind of key value system for you ids, so that you can relate back to the appropriate database row for updates. You just need to parse out text aspects of the id on the backend.
January 12th, 2010 at 3:46 am
[...] Table Drag and Drop JQuery plugin [...]
January 13th, 2010 at 1:52 pm
Nino printed some work back in 08 on how to use with scrollable div. Seems (prob due to cut-n-paste issues) to be problematic. does anyone have this effort functional? New (sadly) to all this javascript/jquery so I’m weak and learning but need to use something like this
Any help appreciated – Thanks!
January 15th, 2010 at 2:13 pm
Hi
very nice script
can anybody help on the following senerio
i am having one html table inside the div and i am trying to drag the rows its working for me but the vertical div scroll is not working if the selected ro dragged at the end of the div
please give me any solution
thanks
irfan
January 17th, 2010 at 11:11 pm
Good stuff.
To drag only when using the left button, insert
if (ev.which != 1) { return false; }at the beginnig of the two
.mousedown(function(ev) { (...)handlers.the which property is provided by jQuery, so no need to worry about compat.
Also, since “dragObject” is not assigned, there is no need to modify the *move and *up events.
January 20th, 2010 at 11:35 pm
very good
but i want to drag and drop / and then to vote … i can do this ?
i want this for an top 20 music
you can help me pls ?
January 21st, 2010 at 6:35 am
Hi guys,
Thanks for this great script !
I need to implement a sortable list (with drag n’ drop). It works fine.. but I need to use pagination to navigate through the list.
Do someone have an idea on how to implement this drag n’drop script with a pagination ?
Many thanks,
Chris
January 21st, 2010 at 7:31 am
I know that people have been asking for a while how to drag table bodies, instead of just individual rows. I needed this functionality for a project, so I spent some time figuring out how to implement the solution.
It turns out that this requires relatively minor changes to the script. By changing the two lines below, you can drag table bodies just as you drag rows. If you use this solution, you will have to enclose even individual rows in tags. However, the nice part is that you can drag multiple rows as if they were a single row.
line 130: jQuery.tableDnD.dragObject = this.parentNode.parentNode;
line 285: var rows = jQuery.tableDnD.currentTable.tBodies;
January 22nd, 2010 at 8:13 am
[...] Table drag and drop jQuery plugin – Link. [...]
January 26th, 2010 at 11:23 pm
Can anyone suggest me how to drag multiple rows?
January 28th, 2010 at 3:20 pm
Hi Jon Can you please provide me the script you used for dragging and dropping multiple rows
January 30th, 2010 at 5:54 am
Hi Rocky,
The solution I posted should work for you, if you are using the version of tablednd from this site.
You will need to enclose individual rows in tags, in addition to enclosing multiple sets of rows.
So for example:
row-one
row-two
row-three
Let me know if it is still not working, and I can paste the complete script. However, I only made the two changes above.
January 30th, 2010 at 6:08 am
I think I see the problem….my code only works if you use a drag handle. I will have to make another tweak in another place if you aren’t using a draghandle. Let me know if this is what you need.
February 1st, 2010 at 3:39 pm
Excellent script. Was initially confused that there are two versions of the script – one for use with jQuery, and one without. This explained the “tableDnD is not a function” error message I was getting when trying to use the non-jQuery version…
February 5th, 2010 at 4:15 pm
Jon – Thanks for your tweaks to enable the selction of multiple rows using the Drag Handle. You mentioned that it could work without the use of the Drag Handle. Would you be so kind as to show us to make it work without the use of the drag handle?
Thanks!
February 9th, 2010 at 10:15 am
Thank You for this precious litte tool. Helped a lot
February 11th, 2010 at 6:01 pm
Cool script. Love it.
I want to be able to use your script to nest rows under their parent rows. Is this possible?
Example:
row1
row2
row2.1
row2.2
row3
row4
row4.1
row4.2
row5
February 11th, 2010 at 8:29 pm
Hi Jon Can u please post the script?
Appreciate your help.
Have a Great day
February 12th, 2010 at 9:15 am
Here is a link to my script.
http://www.878282v6y7k.com/dev/
I would like to be able to nest rows under their parent rows. Something like this.
[drag] Sports 2 Yes
—[drag] Golf 2 Yes
—[drag] Football 2 Yes
—[drag] Baseball 2 Yes
[drag] Tech 2 Yes
—[drag] Mobile 2 Yes
February 15th, 2010 at 5:32 am
If you change line 142 to:
var rows = jQuery(“tbody”, table); // get all the rows as a wrapped set
…that should work to drag tbodies with any td. You will also have to make this change I posted earlier to line 285:
var rows = jQuery.tableDnD.currentTable.tBodies;
That should work for dragging tbodies when draghandle is not specified. I haven’t had time to test this thoroughly…so there might be bugs. I have done most of my work with the drag handle functionality enabled.
Hope that helps. Let me know if there are problems.
February 15th, 2010 at 8:35 am
Any news on dragging between tables?
With two tables (left and right) I can implement something like ‘available’ and ’selected’ by dragging rows from left to right table and sorting the selected items by dragging a row up and down in the richt table
February 17th, 2010 at 6:28 am
Hi
I want to drag drop rows between two tables
Can this possible.
If yes please send me th code
February 19th, 2010 at 8:49 am
Thanks for nice script, but i want the swaping of rows, means if the inicially the arrangement is
r1
r2
r3
r4
then
if i drag r4 to r1 then the arrangement will be
r4
r2
r3
r1
February 20th, 2010 at 7:23 am
Hey Everyone,
First of all, I’d like to give props to DenisH for the great plug-in! It really saved my a lot of time on a Form Builder project I’ve been working on recently. I am, however, disappointed to see that development on TableDnD seems to have come to a halt, but I know how it is maintaining free software — a thankless job to some degree.
Anyway, the main reason I’m posting is to share a minor modification I made to your script. After I coded this “hack” (which took only about 20 minutes, thanks to your fantastic API), I realized that it’s not that uncommon a need, and that other developers might be wishing there was a similar feature implemented.
Basically, I needed to prevent the onDragStart callback from being called just because of a quick, single click on a drag-able row. What I mean is, I didn’t want my onDragStart callback being called when the user was just CLICKING on the row, and NOT trying to actually drag the row around. In the Form Builder script I’m developing, the onDragStart callback causes the inline “Edit Question” form to be hidden, which is required if your dragging a row — but just irritating if you don’t intend to actually drag it. So basically, this little mod just makes the script a little more intuitive (IMO), and helps to determine what the users intent was (to drag, or simply click?).
To implement this, I modified the makeDraggable method in the plug-in itself. Inside the conditional that checks to see if an onDragStart callback is specified, I added a few lines. First the mouse offset position (Y cord only) is stored when the dragCell is initially clicked. Then, bind a callback to the “mousemove” event on the dragCell element. When mousemove fires, I simply get the new mouse offset Y cord, then check to see if it’s changed (increased or decreased) by at least 2 pixels (you could easily change it to however many pixels). If it has, the onDragStart callback is called, otherwise it’s not. In either case, I DO clean-up by unbinding the mousemove callback.
I hope someone may find this snippet helpful. I thought it was a useful little enhancement. Please do note, the code I’ve included ONLY works if your using a dragCell (not the entire row). However, one could easily take my code snippet and move it into the else statement a few lines below which is for those not using a dragCell. I just didn’t need that.
If anyone needs some help with this, feel free to drop me a line at snconners@gmx.co.uk, as I don’t frequent DenisH’s blog often.
————–
Grab TableDnD v0.5 with my mod here: http://pastebin.com/f31a6ee99
Or, here’s just the modified code itself, starting around line 146 of v0.5:
jQuery(this).mousedown(function(ev)
{
jQuery.tableDnD.dragObject = this.parentNode;
jQuery.tableDnD.currentTable = table;
jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
/*
** Only call onDragStart if
** mouse moves > 2px (on Y)
*/
if(config.onDragStart)
{
var startOffset = jQuery.tableDnD.mouseOffset.y;
jQuery(this).bind(“mousemove”, function(ev)
{
var newOffset = jQuery.tableDnD.getMouseOffset(this, ev).y;
if(newOffset > startOffset + 2 || newOffset < startOffset – 2)
{
config.onDragStart(table, this); // Call onDragStart callback
}
});
}
return false;
});
February 25th, 2010 at 10:36 am
i have just used the table DND and saved sort-list in cookies. That means the sor-list can be reloaded on table-sort initing later.
The sort-function can be inserted in build block of tableDnD main codes.
$(document).ready(function() { // Initialise the table $(".tbl").tableDnD({ onDragClass: "myDragClass", onDrop: function(table, row) { var rows = table.tBodies[0].rows; var orderStr = ""; for (var i = 0; i < rows.length; i++) { orderStr += rows[i].id + ";"; } $(".test").html(orderStr); $.cookie("order_"+ $(".plabel").text(), orderStr, { expires: 30}); }, containerDiv: $("#viewContent") }); $(".test").html($.cookie("order_"+ $(".plabel").text())); });February 25th, 2010 at 11:24 am
Hallo Nino Dafonte,
your codes of “TableDnd in Scrolled Div” have a bug, that the scroll can only be scrolled down. Scroll up is not working . The codes shuld be changed like so:
var container = config.containerDiv; var yOffset = container.scrollTop(); var windowHeight = container.innerHeight(); var y = mousePos.y - jQuery.tableDnD.mouseOffset.y; var upperBorder = container.position().top + container.innerHeight(); // not error, it should also be added because mouse moves up var bottomBorder = container.position().top + container.innerHeight(); if (mousePos.y > bottomBorder) { container.scrollTop(container.scrollTop() + config.scrollAmount); } if (mousePos.y < upperBorder) { container.scrollTop(container.scrollTop() - config.scrollAmount); }February 26th, 2010 at 3:42 pm
It is possible now drag and drop under parent rows?
Thanks.
February 26th, 2010 at 4:43 pm
Great script! Do you have any plan to add drag/drop column instead of row?
February 28th, 2010 at 12:01 am
I have a problem with this plugin when using dragHandle.
If you stay with the cursor with mousedown just between 2 td’s the drag image will appear on both.
It’s very annoying. :/
Anyone could help me fix it? I’ve tried alot and I don’t think this plugin will be updated anymore, right?
Thanks
February 28th, 2010 at 12:15 pm
Also, I can’t get tableDnDUpdate() working ;/
March 6th, 2010 at 10:34 am
I was able to get the multi-tbody functionality working with a little effort:
Modify code near line 270:
if (currentRow) { // same tbody if (jQuery.tableDnD.dragObject.parentNode == currentRow.parentNode) { // make sure we've moved if (jQuery.tableDnD.dragObject != currentRow) { if (movingDown) jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling); else if ( !movingDown) jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow); } } // different tbody else { var tmpObject = jQuery(jQuery.tableDnD.dragObject).detach(); if (movingDown) tmpObject.insertBefore(jQuery(currentRow)); else if ( !movingDown) tmpObject.insertAfter(jQuery(currentRow)); } }Note: requires jquery 1.4! (the detach() method makes the magic happen…)
Regards,
Landon
March 7th, 2010 at 2:20 am
[...] 7. Table row drag and drop This TableDnD plugin allows the user to reorder rows within a table, for example if they represent an ordered list (tasks by priority for example). Individual rows can be marked as non-draggable and/or non-droppable (so other rows can’t be dropped onto them). Rows can have as many cells as necessary and the cells can contain form elements. [...]
March 9th, 2010 at 5:36 am
Hy I Have found bug in the table drag and drop plugin.
i fill the div’s Inner Html with xajax function after words in xajax i called addScript() function to add dynamic script.table is sortable and dragable in any ie,mozilla and opera browser.
but this cant work in the safari 3+. & i found the following error or alert message
Type Error: Value undefined(result of expression o.find) is not object.
Please help me asap.
March 9th, 2010 at 6:22 am
First off, thanks so much for the plugin. It is really useful and easy to use.
I have a problem when I have a table inside an iframe. When I drag a row and take it to the top, the page will not scroll (even after explicitly setting scrollAmount to a positive value). Scrolling works on the same table if it is not inside an iframe. Has anyone faced this problem? Has anyone figured out a solution for this?
Thanks in advance.
March 11th, 2010 at 2:03 pm
[...] Table Drag and Drop JQuery plugin [...]