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?

  1. Download Download jQuery (version 1.2 or above), then the TableDnD plugin (current version 0.5).
  2. Reference both scripts in your HTML page in the normal way.
  3. In true jQuery style, the typical way to initialise the tabes is in the $(document).ready function. Use a selector to select your table and then call tableDnD(). 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 using onDragClass.) The CSS style to apply is specified as
a map (as used in the jQuery css(...) 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 is tDnD_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: , ,

434 Responses to “Table Drag and Drop JQuery plugin”

  1. Nathan Says:

    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!

  2. Nathan Says:

    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;
        	}
    
  3. Nathan Says:

    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!

  4. Nathan Says:

    Hmm, that else statement should state: (I’ll try again!)

    else	// search for where it was dropped on
     for (var i=0; i 0 && rows[i-1].id == row.id)
       droppedon = rows[i].id;
    

    Okay, sorry for so many comments, I just really like your plugin!

  5. Nathan Says:

    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 )

  6. Nathan Says:

    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;
    }
    });
    }

  7. Nathan Says:

    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!

  8. Nathan Says:

    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….

  9. Nathan Says:

    Meant to add, alert($(“#queueTable”).attr(‘class’)); never reports the “myDragClass” mid-drag.

  10. DenisH Says:

    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?

  11. Sorting table rows with jQuery and ColdFusion « musings Says:

    [...] using the jQuery sortables plugin. I was asked how this could be done with table rows. The jQuery TableDnD plugin comes to the [...]

  12. DenisH Says:

    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 :-)

  13. Kevin Says:

    Will this have row ghosting and serializing soon? Like the Sortables, anything being dragged should be ghosted… if you know what I mean.

  14. DenisH Says:

    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.

  15. Skylog » Blog Archive » links for 2008-02-29 Says:

    [...] Table Drag and Drop JQuery plugin | Isocra (tags: jquery) [...]

  16. ShaunS Says:

    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 1
    

    And have the ability to move the sub-elements to other sub-elements or main-elements.

  17. Ajax Noticias Novidades tudo sobre Ajax » Arquivo » Drag e Drop em tabelas com jQuery Says:

    [...] 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 … [...]

  18. Table Drag and Drop JQuery plugin | Isocra Says:

    [...] Table Drag and Drop JQuery plugin | Isocra AJAX Scripts Add comments Table Drag and Drop JQuery plugin | Isocra. [...]

  19. Snowcore Says:

    It’s very powerful thing, thanks a lot!

  20. Deja Vu Says:

    Why don’t you make the nodrag/nodrop classes instead of attributes that prevent the markup from being valid ?

  21. Deja Vu Says:

    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.

  22. Famic Says:

    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 drag
    

    Feel free to implement this in the next version if you like valid html ;)

  23. DenisH Says:

    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.

  24. Famic Says:

    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 ;)

  25. Frameshift Says:

    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

  26. Frameshift Says:

    I meant a specific “td” but I put the bracets around it :/

  27. Famic Says:

    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 object
    

    It might not be the best way to do it, but it works fine…

  28. Logan Says:

    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

  29. Logan Says:

    oops, the html of table got striped. let me clarify here, there is a table has one thead tag, serveral tbody tags in it.

  30. DenisH Says:

    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.

  31. Rick Faircloth Says:

    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

  32. Rick Faircloth Says:

    Oops, wrong author reference.
    Should have been, “Hi, DenisH” ! Sorry

    Rick

  33. Lesmana Says:

    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.

  34. Paul Says:

    Just in case anyone is confused as to why something like

    .myDragClass {
    background: #ffc;
    }

    isn’t working, you’ll need:

    .myDragClass td {
    background: #ffc;
    }

  35. Serhio Says:

    Is anyone create some php id script update? I was trying to link eveything but unsuccessful… :(

  36. Just Says:

    Just to say : thanks ;) .

  37. iSmart Says:

    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).

  38. Jaha Says:

    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.

  39. Jaha Says:

    nevermind they had the info on the site i previously posted

    I am interested in the ghosting though, has anyone made any progress?

  40. nathan Says:

    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.

  41. DenisH Says:

    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.

  42. nathan Says:

    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.

  43. Khara Says:

    Is there a way to disable certain rows (tr) from being moved?

  44. DenisH Says:

    Yes, if you add an attribute called “NoDrag” to the row, so you have
    … then the row shouldn’t be draggable, however this means that the HTML isn’t strictly correct, so in the next version I’m going to change this so that you can use a class instead, or define your own method. But for now, that should work fine.

  45. Simon Says:

    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?

  46. DenisH Says:

    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.

  47. kai Says:

    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.

  48. DenisH Says:

    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?

  49. kai Says:

    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.

  50. DenisH Says:

    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
    });
    
  51. kai Says:

    Perfect! That’s what I was missing, wicked awesome ;)

    Thanks again for your help…

  52. Phil Says:

    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;
            }
    
        }
    
  53. centralb Says:

    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

  54. DenisH Says:

    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

  55. JayJay Says:

    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!

  56. DenisH Says:

    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!

  57. nathan Says:

    Thanks Denis, I enjoy experimenting with all these new features!

  58. Zbynja Says:

    Hi, your plug-in is really brilliant !! I love it!
    Thank you much for your effort.

  59. iHao Says:

    good job.
    just i needed!

  60. Sara Says:

    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!)

  61. smilypie Says:

    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…

  62. andy Says:

    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

  63. DenisH Says:

    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.

  64. sb Says:

    This is great. Simple, light-weight, easy to implement. Thank you!

  65. James Nylen Says:

    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.

  66. James Nylen Says:

    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.

  67. Andrew Says:

    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

  68. Jeroen Says:

    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!

  69. uweiss Says:

    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

  70. Francois Levesque Says:

    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!

  71. John Says:

    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!

  72. Joe D'Agostino Says:

    Awesome work. How about a drag drop for columns?

  73. Ewald Says:

    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?

  74. Yuri Says:

    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'));
    }
    
  75. Foppe Hemminga Says:

    You want to replace $ by jQuery in lines 108 and 261.

  76. DenisH Says:

    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.

  77. Jacob Abshire Says:

    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?

  78. erkunt karabulut Says:

    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

  79. erkunt karabulut Says:

    into the document.write is

    document.write();

  80. erkunt karabulut Says:

    sorry into the document.write is not seen.

    in it there is input hidden tag. value is serialize

  81. DenisH Says:

    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.

  82. DenisH Says:

    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.

  83. Sven Says:

    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. !?

  84. Sven Says:

    I also did add the debugArea …

  85. Sven Says:

    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?

  86. Sven Says:

    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());
    }
    
  87. Sven Says:

    AND remove the # character in the $(#debugArea).html(“string”) lines;

  88. Lucas Says:

    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!

  89. DenisH Says:

    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

  90. Lucas Says:

    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.

  91. Lucas Says:

    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?

  92. Lucas Says:

    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?

  93. DenisH Says:

    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.

  94. Tabelle "Sortable" machen mit Scriptaculous - AJAX (Asynchronous JavaScripting and XML) Forum Says:

    [...] Vielleicht hilft das ja: Table Drag and Drop JQuery plugin | Isocra [...]

  95. Sunil kumar Says:

    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?

  96. Nathan Says:

    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)

  97. Nathan Says:

    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.

  98. Rey Bango Says:

    @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

  99. Bryan Says:

    Hi,

    This is really a great tool…

  100. Bryan Says:

    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());
    });

  101. DenisH Says:

    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.

  102. jQuery Table sorter | Paul Richards Says:

    [...] Table Drag and Drop Web site [...]

  103. Bryan Says:

    @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.

  104. Bryan Says:

    @Denish [thank you for the immediate reply] i mean. sorry for the typo error on the previous post. :)

  105. Juraj Says:

    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

  106. Juraj Says:

    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.

  107. DenisH Says:

    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!

  108. Juraj Says:

    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 :D

    All working now.

    Excellent plugin. Pint of beer for you ;)

    Juraj

  109. Juraj Says:

    Not sure if anyone requested this but “refresh” would be useful as well as I keep dynamically adding rows.

    Cheers
    Juraj

  110. djot Says:

    -
    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
    -

  111. Neville Franks Says:

    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

  112. Collection Of Cool And Free Ajax Scripts | badeziner Says:

    [...] Table Drag and Drop JQuery plugin [...]

  113. nickD Says:

    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

  114. tgogoi Says:

    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!!!

  115. arian Says:

    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

  116. Pawel - Poland Says:

    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 :)

  117. links for 2008-07-04 « toonz Says:

    [...] Table Drag and Drop JQuery plugin | Isocra (tags: jquery table drag) [...]

  118. roScripts - Webmaster resources and websites Says:

    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…

  119. Jesús Ricarte - Blog » Blog Archive » Tablas más usables con jQuery Says:

    [...] Table Drag and Drop: Como su propio nombre indica, permite arrastrar mover las filas de una tabla para ordenarlas a gusto del usuario. [...]

  120. Steven Hoefel Says:

    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.

  121. Steven Hoefel Says:

    Forget what I just wrote and look for Famic’s post on “dragger”; much tidier.

  122. Nils Ellingsen Says:

    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! :) ).

  123. pligg.com Says:

    JQuery Drag and Drop…

    Rearanjeaza randurile unui tabel prin Drag and Drop cu libraria jQuery…

  124. DenisH Says:

    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

  125. links for 2008-07-12 | JeremiahTolbert.com Says:

    [...] Table Drag and Drop JQuery plugin | Isocra (tags: jquery javascript plugin tables) [...]

  126. 20080713 網摘 - Google 虛擬世界 - 網絡暴民 Jacky’s Blog Says:

    [...] Table Drag and Drop JQuery plugin [...]

  127. arian Says:

    Thanks Denish :)

  128. Adam Says:

    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?

  129. Adam Says:

    Never mind I figured out what I did wrong.

    I need to create a blank style to start out with.

  130. James Byers Says:

    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.

  131. James Byers Says:

    “foo” in my previous comment should have looked like <a…><b>foo</b></a>

  132. Drag & Drop via JQuery & Ajax --> Geht nicht :( - php.de Says:

    [...] 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 __________________ [...]

  133. Cesar Says:

    @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.

  134. DenisH Says:

    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.

  135. kahfei Says:

    Oops..sorry, not sure why my comment appear as posted by DenisH, :-) . the above comment is from me.

  136. DenisH Says:

    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 if
    

    Hope this helps!

  137. Ravi Says:

    >>>0.5 2008-07-11 Now supports having a column as a drag handle

    So you mean columns are switchable by dragging now???

  138. DenisH Says:

    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.

  139. kahfei Says:

    Hi DenisH,

    Million thanks, will try to adapt that to my code. :-)

  140. euro Says:

    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

  141. Fiaz Says:

    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.

  142. DenisH Says:

    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.

  143. Fiaz Says:

    Yep.. i store the original order in the onDragStart event and compare in the onDrop event. Thanks! :)

  144. Fiaz Says:

    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

  145. Kev Says:

    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?

  146. Kev Says:

    sorry was trying to write table and tbody, is it possible for the table drag and drop plugin to work in this way?

    .
    .

  147. Roger Says:

    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! :)

  148. Paul Richards Says:

    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.

  149. Zbiór skryptów AJAX/Javascript/Dhtml. (50+) | Darmowe skrypty, programowanie, informacje domeny Says:

    [...] Table Drag and Drop [...]

  150. Zbiór skryptów AJAX/Javascript/Dhtml. (50+) | Darmowe skrypty, programowanie, informacje domeny Says:

    [...] Table Drag and Drop [...]

  151. ralphjoson » Blog Archive » Cool jquery plugins Says:

    [...] Table Drag and Drop – This TableDnD plugin allows the user to reorder rows within a table [...]

  152. Nino Dafonte Says:

    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;
        },
    
  153. Nino Dafonte Says:

    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,

  154. Nino Dafonte Says:

    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);
            });
    
  155. Nino Dafonte Says:

    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;
        },
    
  156. Kutay Says:

    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?

  157. Rowan Says:

    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;
        }
    
  158. Thomas Angelbo Christensen Says:

    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.

  159. Aaron Says:

    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?

  160. Julie Says:

    Thank you so much! This is wonderful!

  161. Vinicius Cruz » jQuery, o que é isso? Says:

    [...] 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 [...]

  162. Usable Development and Design » Drag-and-drop table rows with jQuery Says:

    [...] 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, [...]

  163. DenisH Says:

    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.

  164. Jordan Says:

    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!

  165. Paul Wootton Says:

    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

  166. Patrick Says:

    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.

  167. Patrick Says:

    Ignore my last comment. I didn’t read the version history.

  168. Nathan Says:

    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.

  169. DenisH Says:

    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! :-)

  170. Zelf Says:

    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.

  171. DenisH Says:

    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?

  172. Zelf Says:

    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.

  173. PeteOH Says:

    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!

  174. PeteOH Says:

    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.]

  175. DenisH Says:

    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

  176. John Says:

    lol @ nathan at the start of the comments…

    ps. Great script! well done =)

  177. Jean-Ba Says:

    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

  178. Jason Says:

    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

  179. John Says:

    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

  180. Stephen Says:

    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.

  181. Terry Says:

    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

  182. Jeroen Says:

    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!

  183. Jeroen Says:

    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…

  184. Sven Fuchs Says:

    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

  185. Vivek Selvaraj Says:

    Thats excellent.. Is it possible to drag and drop a row from one grid to another?

  186. Courtney Says:

    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.

  187. degro Says:

    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

  188. degro Says:

    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.

  189. Adexcube Says:

    Hi, is there any way to serialize only certain rows? For example only those with certain class or element inside?

    Thanks

  190. James Bebbington Says:

    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.

  191. Pau Says:

    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.

  192. Per Cederqvist Says:

    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.

  193. Sam Burdge Says:

    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.

  194. Open Tutor Says:

    How a single cell can drag and drop… pls help.
    -Shaon
    Open tutor Admin
    http://intelisoftbd.com/forum/

  195. Vik Rubenfeld Says:

    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.

  196. Vik Rubenfeld Says:

    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;
    			}));
    
  197. BenCurtis.com » Drag and Drop Sorting with JQuery and Rails Says:

    [...] 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 [...]

  198. pligg.com Says:

    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…

  199. Ben Mills Says:

    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.

  200. Ben Mills Says:

    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.

  201. Smacky Says:

    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);
    }
    }

  202. Leif Says:

    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?

  203. ted Says:

    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!

  204. ted Says:

    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!

  205. ted Says:

    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.

  206. Andrea Says:

    Great work!

    Now jquery is clearer than before!

    Andrea

  207. ted Says:

    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+.

  208. Helmut Says:

    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?

  209. Vlad Says:

    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?

  210. Vlad Says:

    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”

  211. Dharmendra Says:

    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 ?? ?

  212. Helmut Says:

    @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() }});

  213. Paul Says:

    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!

  214. Diego Says:

    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.. :(
    I dont know what to do without the serialize… :( help me please..!!!! :(
    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');
    		});
    
    });
    
  215. Diego Says:

    the previous comment contain two slashes on ids hove function but are only to scape php..

    helpme please.. :S

  216. Diego Says:

    woooooorrrrkssss!!!!!!! sorry… a simple mine error..!!! can delete my coments if you want..!! this script works great..!! congratulations..!!!!! :D :D :D

  217. computerzworld Says:

    Hello,
    Is it possible to move the table rows from one table to another? If yes then how? Please help me. Thanks in advance.

  218. Jeremy Says:

    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?

  219. Jeremy Says:

    Nevermind, just discovered tableDnDUpdate(); thanks!

  220. Escartiz Says:

    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();
    ?>
    
  221. Escartiz Says:

    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 . >;
    }

  222. Escartiz Says:

    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

  223. Escartiz Says:

    everything seems fine only that when submiting the form i refreshing the table the order of appearance stays the same

  224. Shani elharrar Says:

    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…

  225. Askioneer Says:

    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!

  226. Spir Says:

    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.

  227. luar gomez Says:

    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

  228. SMalldevil Says:

    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 ?

  229. Spir Says:

    SMalldevil > use liveQuery
    http://brandonaaron.net/docs/livequery/

    It should helps

  230. Spir Says:

    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

  231. SMalldevil Says:

    Spir > Have you already use livequery for this table drag and drop ? Have you a demo script ?

  232. SMalldevil Says:

    because with my custom script doesn’t works http://inova.tech.free.fr/LIVEQUERY/ help me.

  233. Cameron Says:

    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.

  234. Cameron Says:

    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

  235. Cameron Says:

    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);

  236. Spir Says:

    SMalldevil> See this. But I had some issues setting it.

    $(document).ready(function(){
    $(“#table-1″).livequery(function(){
    $(this).tableDnD({
    … options …
    });
    });
    });

    Bonne chance

  237. Tony Says:

    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

  238. Simon Says:

    Very nice! Thank you very much
    that could be useful for my new projekt

  239. Frank Maulit Says:

    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!

  240. Oliver Schlöbe Says:

    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!

  241. Gustavo Says:

    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”);

  242. Gustavo Says:

    var chart = new FusionCharts(“../dmkitimages/MSBar2D.swf”, “ChartId”, “350″, “375″, “0″, “0″);
    chart.setDataURL(“../dmkitimages/Data/MSBar2D.xml”);
    chart.render(“chartdiv”);

  243. ViAm Says:

    In my table, i have 3 rows selected with class=’sel’. I want to drag only these rows. How do I do it?

  244. Kender Says:

    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…

  245. vb Says:

    so can i do that in vb forums

  246. saving sequence order of files | keyongtech Says:

    [...] 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 [...]

  247. Cameron Says:

    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!

  248. Cameron Says:

    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.

  249. bbc Says:

    cool work

  250. izarco Says:

    what about a reorder with sublevels??
    Example:

    Main 1
    Main 2
    Main 3
        Sub 1
        Sub 2
        Sub 3
    Main 4
        Sub 1
    

    Great job!

  251. niko Says:

    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');
    	});
    
  252. Jason Says:

    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.

  253. Alex Says:

    I want to disable grabbing a row while the ajax is processing – - any quick way to do this?

  254. Neeraj Says:

    Thanks for this great plugin…. But im facing one problem that this plugin is working on firefox but not on ie ….

  255. suresh Says:

    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
    Fourteen
    

    I need this urgent for my project. Please help me.

  256. suresh Says:

    Hi all,
    When i am trying to drag with in the scroll, it will not work properly.

    suresh.p

  257. Alex Says:

    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.

  258. Jonny Says:

    Yeah…I’m experiencing the same issues in IE8…just when I thought I had a reliable option for sorting!

  259. Jim Says:

    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.

  260. Jim Says:

    Let me word my question differently. How can I keep the functionality as is, but not move the first cell in each row?

  261. suresh Says:

    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

  262. My jQuery impressions - Sonu on .NET Says:

    [...] 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 [...]

  263. netmastan Says:

    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";
    
  264. Eric P. Says:

    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.

  265. Mexis Says:

    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!!!

  266. Mexis Says:

    Nevermind,

    I figured it out!!!
    Thanks….!!

  267. Neil Crookes » CakePHP Sequence Behavior Says:

    [...] 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 [...]

  268. Chetan Says:

    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

  269. Sebastien Says:

    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

  270. Paul Says:

    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!!!

  271. Pablo Says:

    Muchas gracias por el aporte. Desde Paraná – Entre Ríos – Argentina agradezco el plug in.
    Felicitaciones (congratulation)
    Thank you very much!!!

  272. John F Says:

    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.

  273. John F Says:

    Whoops, I just noticed tableDnDUpdate(); mentioned earlier. Sorry!

  274. jonyshah Says:

    can u plz tell me how this drag drop can be maintained in Gridview in ASP.Net 2.0?

  275. jonyshah Says:

    i want to interchange sequnce id of my rows of gridview.
    i hv to maintain it for differetn users and dynamically.

  276. John F Says:

    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

  277. Davin Says:

    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’);
    },

  278. Michael in Boise Says:

    @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.

  279. Douglas Ianitsky Says:

    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
    					}
    	        	}
    			});
    		}
  280. Eric P. Says:

    Ack… nevermind my comments. jQuery UI isn’t even a dependency for this plugin. I goofed.

    Sorry!
    Eric

  281. oo Says:

    Why should I use this plugin? ui.sortable can be applied to tables and does the trick. *confused*

  282. Zach Says:

    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.

  283. Oliver Kohll Says:

    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

  284. IanR Says:

    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

  285. David M Says:

    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

  286. Ted Devito Says:

    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!

  287. Anuraag Says:

    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???

  288. JohnC Says:

    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).

  289. Karl Says:

    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

  290. bloggotika Says:

    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

  291. Helene Says:

    Hi!
    How can I block the table with the event, uses tableDnD?

  292. Adel Says:

    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?

  293. Lonza Says:

    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

  294. geoffrey Says:

    doesnt seem to work in internet explorer 7

  295. seth Says:

    Karl,

    Did you ever get your situation figured out? I’m trying to do something similar.

    Thanks,
    -s

  296. Kuroi Says:

    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

  297. Ertuğrul Erkan Says:

    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.

  298. 228Vit Says:

    A small typo here:
    $(#debugArea).html(debugStr);//no quotes

    must be:
    $(‘#debugArea’).html(debugStr);

  299. Bagus Says:

    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

  300. Niccy Says:

    Sweet! It worked right away! I though i had to convert my table into a list to sort it, but it just worked.. :D

  301. ciro Says:

    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…

  302. Dan Parker Says:

    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>
    
  303. Dan Parker Says:

    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!!

  304. Ronny-André Bendiksen Says:

    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?

  305. DenisH Says:

    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.

  306. Andrew Says:

    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!

  307. VaN Says:

    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 ?

  308. Tims Blog » Blog Archive » Tired. Couldn’t sleep Says:

    [...] table drag and drop jquery plugin [...]

  309. Zadin Says:

    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">&nbsp;</td><td align="center">1</td><td>Data
    1</td></tr>
    <tr id="27"><td class="dragHandle">&nbsp;</td><td align="center">2</td><td>Data
    2</td></tr>
    <tr id="28"><td class="dragHandle">&nbsp;</td><td align="center">3</td><td>Data
    3</td></tr>
    <tr id="30"><td class="dragHandle">&nbsp;</td><td align="center">4</td><td>Data
    4</td></tr>
    <tr id="23"><td class="dragHandle">&nbsp;</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;
    }

  310. Kerry Says:

    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

  311. netin Says:

    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

  312. DenisH Says:

    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:

    1. Ensure that you’re actually including the right javascript files and that they’re being loaded correctly (you need both the core jQuery and the jQuery.tableDnD files as described above). Do this by typing the urls that you’re using directly into the browser bar and checking that you get the javascript back. If you don’t it’s because the url doesn’t match where you’ve put the file.
    2. If you’re using Prototype or MooTools or YUI or any other Javascript library, check that it doesn’t clash with JQuery. Read Using jQuery with other libraries if you need to make them work together
    3. Check that the call you’re making to tableDnD() is actually getting executed. If you’re using $(document).ready(function() {...} then insert alert("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.
    4. Check that the ID of your table matches what you’ve put in the Javascript and that there is only one. So if you’re calling $(‘#table-1′).tableDnD(), check that there is a table with that ID on the <table> element and that there is only one of these.
    5. Look for any Javascript errors that might tell you what is wrong. If you’re using IE, then check in the status bar to see if it’s flagging any errors quietly.
    6. Change the Javascript to $('#table-1 tr:even').css('background', '#ecf6fc'); (with your table ID instead of table-1, but keeping the tr: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.
    7. Use Firefox and install FireBug. You can then set a breakpoint on your Javascript code and see what the problem is. Even if Firefox isn’t your target browser, the Javascript will work the same in IE, Safari, Opera, etc. So debug in Firefox and then check in your target browser. Firebug is also really good at signalling errors and you can use it to check that the the javascript is being downloaded correctly in the page, so it’s basically an essential tool.
    8. If all else fails, put a test page with your code somewhere on the web so that others can access it, and then post a comment here and I or some other kind contributor will have a look and see if we can spot the problem.

    Hope this helps.

  313. max Says:

    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

  314. Itlan Says:

    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.

     _________________
    |icon|Subject_____|
    |____|Preview_____|
    

    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?

  315. Itlan Says:

    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?

  316. Itlan Says:

    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”).

  317. DenisH Says:

    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.

  318. Itlan Says:

    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!

  319. nathan Says:

    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.

  320. jared Says:

    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

  321. jared Says:

    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.

  322. Ryan Hayle Says:

    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.

  323. ZK@Web Marketing Blog Says:

    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?

  324. All About Tables – jQuery Plugin | INSIC 2.0 Web Development & Design Blog Says:

    [...] 3. Table Drag and Drop JQuery plugin [...]

  325. Steve Says:

    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(

  326. Markus Says:

    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);

  327. Claire Says:

    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.

  328. Benny Says:

    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 ??

  329. Claire Says:

    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?

  330. Max Says:

    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

  331. Max Says:

    http://users.wfu.edu/strumc7/DragNDrop/
    sorry about the double post

  332. Daniel Schultz Says:

    I am needing an table to input text drag’n drop.

    I tried to adapt your example with no success.

    Thanks

  333. Daniel Schultz Says:

    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

  334. I need help Says:

    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

  335. DenisH Says:

    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.

  336. Developer Says:

    Hi! Is there a way to select multiple rows and drag them all together?

  337. I need help Says:

    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?

  338. DenisH Says:

    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.

  339. marv100 Says:

    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.

  340. anonymous Says:

    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!

  341. anonymous Says:

    I guess my patch blew up upon posting, oh well.

  342. Lani Says:

    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?

  343. EastGuy Says:

    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?

  344. Duane Says:

    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.

  345. DenisH Says:

    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

  346. DenisH Says:

    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

  347. Duane Says:

    Thanks Denis,
    Thats what I though I just wanted to be sure I wasnt missing something.

  348. EastGuy Says:

    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;
    }

  349. Patrick Says:

    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

  350. Karthik Says:

    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…

  351. DenisH Says:

    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.

  352. Reordering invoice lines using jqGrid and TableDND extension - Gunnar Peipman's ASP.NET blog Says:

    [...] 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 [...]

  353. Justin Kennedy Says:

    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

  354. equ Says:

    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();

  355. Gabe Says:

    What’s the easiest way to call a reorder ASP .NET method?

  356. Jack P Says:

    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”;

  357. Tom Says:

    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.

  358. kellen Says:

    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 tableDnD
    
  359. Alistair Macdonald Says:

    works great for me! Thanks for plug-in

    @Eastguy try using row.rowIndex instead of row.id

  360. Table Drag n Drop Script Says:

    [...] 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: [...]

  361. 15 Great jQuery Plugins For Better Table Manipulation Says:

    [...] 14. Table Drag and Drop jQuery plugin [...]

  362. より良いテーブルのためのjQueryプラグイン15種 | yuxu's notebook Says:

    [...] ColumnManager plugin jQuery treeTable CSV2Table Table Pagination jQuery TableRowCheckboxToggle Table Drag and Drop jQuery plugin uiTableEdit [...]

  363. stuckey Says:

    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!

  364. 15 plugins jQuery para la manipulación de tablas | aNieto2K Says:

    [...] Table Drag and Drop jQuery plugin [...]

  365. stuckey Says:

    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.

  366. Jeff Says:

    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

  367. Jeff Says:

    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
    
  368. Henrik N Says:

    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

  369. ColdFusion Developer Says:

    Nice script. Its too bad Jquery doesn’t support sorting like list elements but this is a great tool nonetheless.

  370. Stuckey Says:

    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!

  371. Val Says:

    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? )

  372. Val Says:

    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.

  373. Val Says:

    oops, the example should be:

    var i = 1, j = 2, bar = ‘quux’;
    $( ‘#foo tr:eq(i) td:eq(j)’ ).val( bar );

  374. Stuckey Says:

    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.

  375. Stuckey Says:

    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>

  376. Henrik N Says:

    Stuckey: you could define an ondrop callback that does something like: $(“#foo tr”).each(function(index) { $(this).find(“.number”).html(index+1); });

  377. Best jQuery Plugins For Better Table Manipulation | guidesigner.net Says:

    [...] Table Drag and Drop jQuery plugin [...]

  378. formato para tablas con jquery (15 formas) « Jarivia 3D, blog de investigacion 3d interactiva para web Says:

    [...] sitio de Table Drag and Drop jQuery plugin» [...]

  379. Vincent Says:

    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”);

  380. richard Says:

    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?

  381. canman Says:

    Did anyone ever manage to get sub-levels supported?

  382. leohakim.com.ar/blog » 15 plugins jQuery para manejar tablas Says:

    [...] Haz clic aquí para ingresar al sitio de Table Drag and Drop jQuery plugin» [...]

  383. jQuery ColorPicker + Table Drag and Drop - MIEO Blog Says:

    [...] jQuery Table Drag and Drop (tablednd) [...]

  384. Greg Gorman Says:

    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:

    /**
    * TableDnD plug-in for JQuery, allows you to drag and drop table rows
    * You can set up various options to control how the system will work
    * Copyright (c) Denis Howlett
    * Licensed like jQuery, see http://docs.jquery.com/License.
    *
    * Configuration options:
    *
    * 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 using onDragClass.) The CSS style to apply is specified as
    *     a map (as used in the jQuery css(...) 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 is tDnD_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.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.
    * onAllowDrop
    *     Pass a function that will be called as a row is over another row. If the function returns true, allow
    *     dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under
    *     the cursor. It returns a boolean: true allows the drop, false doesn't allow it.
    * 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
    * dragHandle
    *     This is the name of a class that you assign to one or more cells in each row that is draggable. If you
    *     specify this class, then you are responsible for setting cursor: move in the CSS and only these cells
    *     will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where
    *     the whole row is draggable.
    *
    * Other ways to control behaviour:
    *
    * Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows
    * that you don't want to be draggable.
    *
    * Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form
    * []=&[]= so that you can send this back to the server. The table must have
    * an ID as must all the rows.
    *
    * Other methods:
    *
    * $("...").tableDnDUpdate()
    * Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells).
    * This is useful if you have updated the table rows using Ajax and you want to make the table draggable again.
    * The table maintains the original configuration (so you don't have to specify it again).
    *
    * $("...").tableDnDSerialize()
    * Will serialize and return the serialized string as above, but for each of the matching tables--so it can be
    * called from anywhere and isn't dependent on the currentTable being set up correctly before calling
    *
    * Known problems:
    * - Auto-scoll has some problems with IE7  (it scrolls even when it shouldn't), work-around: set scrollAmount to 0
    *
    * Version 0.2: 2008-02-20 First public version
    * Version 0.3: 2008-02-07 Added onDragStart option
    *                         Made the scroll amount configurable (default is 5 as before)
    * Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes
    *                         Added onAllowDrop to control dropping
    *                         Fixed a bug which meant that you couldn't set the scroll amount in both directions
    *                         Added serialize method
    * Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row
    *                         draggable
    *                         Improved the serialize method to use a default (and settable) regular expression.
    *                         Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table
    */
    jQuery.tableDnD = {
        /** Keep hold of the current table being dragged */
        currentTable: null,
        /** Keep hold of the current drag object if any */
        dragObject: null,
        /** The current mouse offset */
        mouseOffset: null,
        /** Remember the old value of Y so that we don't do too much processing */
        oldY: 0,
        /** Remember the old value of X so that we don't do too much processing */
        oldX: 0,
        /** keep track of mouse down */
        isMouseDown: false,
        /** keep track of whether or not a drag is actually happening verus a click */
        dragging: false,
        /** how much of a mouse movement is considered a drag */
        dragThreshold: 4,
    
        /** Actually build the structure */
        build: function(options) {
            // Set up the defaults if any
    
            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
                }, options || {});
                // Now make the rows draggable
                jQuery.tableDnD.makeDraggable(this);
            });
    
            // Now we need to capture the mouse up and mouse move event
            // We can use bind so that we don't interfere with other event handlers
            jQuery(document)
                .bind('mousemove', jQuery.tableDnD.mousemove)
                .bind('mouseup', jQuery.tableDnD.mouseup);
    
            // Don't break the chain
            return this;
        },
    
        /** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */
        makeDraggable: function(table) {
            var config = table.tableDnDConfig;
            if (table.tableDnDConfig.dragHandle) {
                // We only need to add the event to the specified cells
                var cells = jQuery("td." + table.tableDnDConfig.dragHandle, table);
                cells.each(function() {
                    // The cell is bound to "this"
                    jQuery(this).mousedown(function(ev) {
                        jQuery.tableDnD.storeCoordinates(ev);
                        jQuery.tableDnD.dragObject = this.parentNode;
                        jQuery.tableDnD.currentTable = table;
                        jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
                        jQuery.tableDnD.isMouseDown = true;
                        if (config.onDragStart) {
                            // Call the onDrop method if there is one
                            config.onDragStart(table, this);
                        }
                        return false;
                    });
                })
            } 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() {
                    // 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.storeCoordinates(ev);
                                jQuery.tableDnD.dragObject = this;
                                jQuery.tableDnD.currentTable = table;
                                jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
                                jQuery.tableDnD.isMouseDown = true;
                                if (config.onDragStart) {
                                    // Call the onDrop method if there is one
                                    config.onDragStart(table, this);
                                }
                                return false;
                            }
                        }).css("cursor", "move"); // Store the tableDnD object
                    }
                });
            }
        },
    
        updateTables: function() {
            this.each(function() {
                // this is now bound to each matching table
                if (this.tableDnDConfig) {
                    jQuery.tableDnD.makeDraggable(this);
                }
            })
        },
    
        /** Get the mouse coordinates from the event (allowing for browser differences) */
        mouseCoords: function(ev) {
            if (ev.pageX || ev.pageY) {
                return { x: ev.pageX, y: ev.pageY };
            }
            return {
                x: ev.clientX + document.body.scrollLeft - document.body.clientLeft,
                y: ev.clientY + document.body.scrollTop - document.body.clientTop
            };
        },
    
        /** store the mouse down coordinates */
        storeCoordinates: function(ev) {
            var coords = jQuery.tableDnD.mouseCoords(ev);
            jQuery.tableDnD.oldX = coords.x;
            jQuery.tableDnD.oldY = coords.y;
        },
    
        /** Given a target element and a mouse event, get the mouse offset from that element.
        To do this we need the element's position and the mouse position */
        getMouseOffset: function(target, ev) {
            ev = ev || window.event;
    
            var docPos = this.getPosition(target);
            var mousePos = this.mouseCoords(ev);
            return { x: mousePos.x - docPos.x, y: mousePos.y - docPos.y };
        },
    
        /** Get the position of an element by going up the DOM tree and adding up all the offsets */
        getPosition: function(e) {
            var left = 0;
            var top = 0;
            /** Safari fix -- thanks to Luis Chato for this! */
            if (e.offsetHeight == 0) {
                /** Safari 2 doesn't correctly grab the offsetTop of a table row
                this is detailed here:
                http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
                the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
                note that firefox will return a text node as a first child, so designing a more thorough
                solution may need to take that into account, for now this seems to work in firefox, safari, ie */
                e = e.firstChild; // a table cell
            }
    
            while (e.offsetParent) {
                left += e.offsetLeft;
                top += e.offsetTop;
                e = e.offsetParent;
            }
    
            left += e.offsetLeft;
            top += e.offsetTop;
    
            return { x: left, y: top };
        },
    
        mousemove: function(ev) {
            if (jQuery.tableDnD.dragObject == null) {
                return;
            }
            if (!jQuery.tableDnD.isMouseDown)
                return;
    
            var mousePos = jQuery.tableDnD.mouseCoords(ev);
            var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
            var x = mousePos.x - jQuery.tableDnD.mouseOffset.x;
    
            //if not currently dragging,
            //see if the mouse moved far enough to be considered a drag
            if (!jQuery.tableDnD.dragging) {
                var draggingX = (Math.abs(x - (jQuery.tableDnD.oldX - jQuery.tableDnD.mouseOffset.x)) > jQuery.tableDnD.dragThreshold);
                var draggingY = (Math.abs(y - (jQuery.tableDnD.oldY - jQuery.tableDnD.mouseOffset.y)) > jQuery.tableDnD.dragThreshold);
                jQuery.tableDnD.dragging = (draggingX || draggingY)
                if (!jQuery.tableDnD.dragging) {
                    return;  //haven't moved far enough yet
                }
            }
    
            var dragObj = jQuery(jQuery.tableDnD.dragObject);
            var config = jQuery.tableDnD.currentTable.tableDnDConfig;
            //auto scroll the window
            var yOffset = window.pageYOffset;
            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;
                }
    
            }
    
            if (mousePos.y - yOffset < config.scrollAmount) {
                window.scrollBy(0, -config.scrollAmount);
            } else {
                var windowHeight = window.innerHeight ? window.innerHeight
                        : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
                if (windowHeight - (mousePos.y - yOffset)  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 currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
                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);
                    }
                }
            }
    
            return false;
        },
    
        /** We're only worried about the y position really, because we can only move rows up and down */
        findDropTargetRow: function(draggedRow, y) {
            var rows = jQuery.tableDnD.currentTable.rows;
            for (var i = 0; i  rowY - rowHeight) && (y < (rowY + rowHeight))) {
                    // that's the row we're over
                    // If it's the same as the current row, ignore it
                    if (row == draggedRow) { return null; }
                    var config = jQuery.tableDnD.currentTable.tableDnDConfig;
                    if (config.onAllowDrop) {
                        if (config.onAllowDrop(draggedRow, row)) {
                            return row;
                        } else {
                            return null;
                        }
                    } else {
                        // If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic)
                        var nodrop = jQuery(row).hasClass("nodrop");
                        if (!nodrop) {
                            return row;
                        } else {
                            return null;
                        }
                    }
                    return row;
                }
            }
            return null;
        },
    
        mouseup: function(e) {
            if (!jQuery.tableDnD.isMouseDown)
                return;  //mouse isn't down, can't be dragging
            jQuery.tableDnD.isMouseDown = false;  //reset it
    
            if (!jQuery.tableDnD.dragging) {
                // If we have a dragObject, then we need to release it,
                jQuery.tableDnD.dragObject = null;
                jQuery.tableDnD.currentTable = null; // let go of the table too
                return;
            }
            jQuery.tableDnD.dragging = false;  //no longer dragging.
    
            if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
                var droppedRow = jQuery.tableDnD.dragObject;
                var config = jQuery.tableDnD.currentTable.tableDnDConfig;
                // If we have a dragObject, then we need to release it,
                // The row will already have been moved to the right place so we just reset stuff
                if (config.onDragClass) {
                    jQuery(droppedRow).removeClass(config.onDragClass);
                } else {
                    jQuery(droppedRow).css(config.onDropStyle);
                }
                jQuery.tableDnD.dragObject = null;
                if (config.onDrop) {
                    // Call the onDrop method if there is one
                    config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
                }
                jQuery.tableDnD.currentTable = null; // let go of the table too
            }
        },
    
        serialize: function() {
            if (jQuery.tableDnD.currentTable) {
                return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable);
            } else {
                return "Error: No Table id set, you need to set an id on your table and every row";
            }
        },
    
        serializeTable: function(table) {
            var result = "";
            var tableId = table.id;
            var rows = table.rows;
            for (var i = 0; i  0) result += "&";
                var rowId = rows[i].id;
                if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) {
                    rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0];
                }
    
                result += tableId + '[]=' + rowId;
            }
            return result;
        },
    
        serializeTables: function() {
            var result = "";
            this.each(function() {
                // this is now bound to each matching table
                result += jQuery.tableDnD.serializeTable(this);
            });
            return result;
        }
    
    }
    
    jQuery.fn.extend(
    	{
    	    tableDnD: jQuery.tableDnD.build,
    	    tableDnDUpdate: jQuery.tableDnD.updateTables,
    	    tableDnDSerialize: jQuery.tableDnD.serializeTables
    	}
    );
    
  385. Petra Says:

    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.

  386. steevenz Says:

    why is not working with jquery 1.3.2? is there any updates? can i download it.. or i can just fixed it thanks..

  387. Pablo Reyes Says:

    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!

  388. Gotovsky Says:

    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.

  389. adam Smith Says:

    this is fun

  390. 網站製作學習誌 » [Web] 連結分享 Says:

    [...] Table Drag and Drop JQuery plugin [...]

  391. duc nguyen Says:

    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.

  392. Dibakar Says:

    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?

  393. .NET i jiné ... : Odkazy z prohlížeče 1.11.2009 Says:

    [...] Table Drag and Drop JQuery plugin – použití TableDnD pluginu [...]

  394. Crossbrowser » You can only go as fast as the slowest component Says:

    [...] 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 [...]

  395. web and variants | Vergleich aktueller JavaScript-Compressoren Says:

    [...] 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 [...]

  396. Improving TableDND usability | Eldanor - We design & build amazing websites and web softwares Says:

    [...] TableDnD jQuery plugin allows the user to reorder rows within a table, for example if they represent an ordered [...]

  397. Eldanor Says:

    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.

  398. alphapapalima Says:

    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??

  399. alphapapalima Says:

    I am using:
    jquery-1.3.2.min.js
    jquery.tablednd_0_5.js

  400. papas Says:

    has anyone implemented or will it be implemented in the future for sub levels / sub items?

  401. Julio Says:

    I can update MYSQL DB :S

    Any GooD Example … ?

  402. Julio Says:

    sorry, i say “I CAN´T”

  403. 12 Useful jQuery Plugins for Working with Tables | Web Design Ledger Says:

    [...] Table Drag and Drop [...]

  404. 12 Useful jQuery Plugins for Working with Tables | Graphic Design Pro Says:

    [...] Table Drag and Drop [...]

  405. Matt Huggins Says:

    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: /^.*$/
    });

  406. Aaron Says:

    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!

  407. Bill Says:

    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

  408. Zapperlot Says:

    Is there any possibility to integrate this fine plugin into TinyMCE ? This would be great for me…

  409. Bas Says:

    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.

  410. krits Says:

    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.

  411. Mike Says:

    Does this plugin support nested lists? Or sub-lists as someone else called it.

  412. NomikOS Says:

    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…

  413. Linz Jose Says:

    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

  414. Avaterera Says:

    Hi. Just wanted to ask about progress implementing dragging between tables…

  415. 12 Useful jQuery Plugins for Working with Tables « Vinayindxb Says:

    [...] Table Drag and Drop [...]

  416. Nilesh J. Macwan Says:

    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

  417. radyo Says:

    Thank you! Very good script!

  418. Seppo Hovi Says:

    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?

  419. Jon Says:

    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.

  420. More on Drag and drop sortable lists using jQuery « hybrid moments Says:

    [...] Table Drag and Drop JQuery plugin [...]

  421. DerekP Says:

    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!

  422. irfan Says:

    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

  423. R Says:

    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.

  424. ValsiS Says:

    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 :D

    you can help me pls ?

  425. Chris Says:

    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

  426. Jon Says:

    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;

  427. jQuery serialscroll | WebDesignExpert.Me Says:

    [...] Table drag and drop jQuery plugin – Link. [...]

  428. Rocky Says:

    Can anyone suggest me how to drag multiple rows?

  429. Rocky Says:

    Hi Jon Can you please provide me the script you used for dragging and dropping multiple rows

  430. Jon Says:

    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.

  431. Jon Says:

    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.

  432. Rob Says:

    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…

  433. Mark Says:

    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!

  434. Jan Says:

    Thank You for this precious litte tool. Helped a lot :)

Leave a Reply