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

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

Tags: , ,

69 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

Leave a Reply