Drag table row to a div with jQuery

One of projects I am working on has a long list of classes in a catalog.  These classes are listed on the screen in a table which is sortable and filterable.  Users search through these classes trying to find ones that they want to register for, when the find one they can click on the “add to cart” button in that classes row.  One of the requirements that I was given for this listing was that users should also be able to drag a row to the cart. jQuery UI’s draggables works very nicely but after doing a quick proof-of-concept test I found that draggables don’t work on on table rows very well.  I couldn’t get jQuery UI to drag anything.

If you check out the documentation you will find a option for a “helper”.  This option can either be set to a string (‘clone’ or ‘original’) or you can provide a function which returns the helper object.  So I wrote up some code to create a div with the selected row in a new table.

helper: function(event){
return $('<div class="drag-cart-item"><table></table></div>')
.find('table').append($(event.target).closest('tr').clone()).end().appendTo('body');
},

Then all you need to do is set up a dropable area that knows how to handle that helper.

('#cart').droppable({
drop: function(event, ui) {
var classid = ui.helper.find('tr').attr('id');
var name = ui.helper.find('.name').html();
$('#cart .selected').append('<li id="'+classid+'">'+name+'</li>');
}
});

Updated Demo using jQuery 1.4.3 and jQuery UI 1.8.5

Check out the working demo



  • http://geekswithblogs.net/apopovsky/ Ariel Popovsky

    Thank you so much, this is what I was looking for. Simple and elegant solution.

  • mester

    good stuff!

  • Rafeequ

    Very helpful.
    But its is not seems to work on IE8.Is there any quick fix ?

    • Chinmayee Misra

      Use 1.71. jquery it will work…

  • http://www.petersendidit.com petersendidit

    Looks you should append the helper to the body before you pass it back, otherwise the jQuery UI draggable will append the helper to the items parent, which in this case is the table. I have updated the post to correct for this.

  • http://www.diabloexile.com/ Wepic

    Good stuff, thanks for the tip!

  • Bob

    This is great :) Thanks for showing me how to use the helper object :)

    I’m sure you’ve noticed, though, that your demo doesn’t work well in Chrome. Notice 1) that a selection occurs while you drag. And also, how 2) the first cell of your table changes widths.

    The fixes are pretty simple, though…

    1) inside your start handler, add the following:
    $(document).bind( ‘selectstart.draggable’, function( ){ return false; } );

    and inside your stop handler, add the following (you already sort of have this):
    $(document).unbind( ‘selectstart.draggable’ );

    2) this problem is caused by the ui library adding the helper element to the parent of the item being dragged. In this case, it results in a DIV being directly appended as a child of a table (only tbody is allowed here, and unofficially, tr). Chrome treats this as if it were a cell instead of a div, and it expands the first column to fit your entire helper object. At some point, the draggable library adds a position:absolute so you can drag the helper around, but not before your table cell size has been messed up. The solution here is simple… set position:absolute on the helper object right away:

    return $(”).find( ‘table’ ).append( origRow.clone( )).end( ).css( { “width”: origTable.outerWidth( ), “position”: “absolute” } );

    Note: the CSS width in the above code is not needed for this fix, but it does add to the aesthetic of the effect by keeping the helper object the same width as the original row you are dragging.

  • http://www.petersendidit.com petersendidit

    @Bob

    The other option is to use jQuery UI’s disableSelection() and enableSelection() functions.

    Example: http://jsfiddle.net/cZare/1/show/

  • tim

    this example is a life saver, except:

    disableSelection() and enableSelection() do not in fact solve the selection issue in my chrome (although the other technique given above does work)

    it seems that something has changed in jquery ui 1.8 to break the example

    the former is just curious, the latter is a show stopper. can someone fill me in?

  • arnab

    there is one problem with chrome..

  • http://www.petersendidit.com petersendidit

    jQuery UI 1.8.5 had a complete rewrite of disableSelection() and enableSelection() with the goal of better cross browser support. I have updated the demo link with a version that should work correctly in Chrome. http://jsfiddle.net/petersendidit/cZare/2/

  • Cryborg

    Hi !

    I know this code is quite old, but it is still very interesting and, moreover, very useful.
    What I would like to do, though, is use it for multi selection. I have a table containing TRs with one checkbox on each. I’d like to “move” the checked lines, but I can’t seem to find the right syntax.

    Can someone help me on this ?

    Thanx !

  • Cryborg

    Hi again !

    I found how to use this code with multiselection, thought I would share it :

    $(‘#ids_fichiers’).droppable({
                drop: function(event, ui) {
                    $(‘#grid’).find(‘input:checked’).each( function (id, elem) {
                        $(‘#ids_fichiers .selected’).append(”+$(elem).closest(‘tr’).find(‘td’).eq(2).text()+”);
                    });
                   
                }
            });

    Maybe there’s something more elegant, but it works for me.

    Hope this can help.

  • Anonymous

    Hi thanks alot for the demo but where or what event would you use to  remove the table row from grid after it is dropped. I tried on drop but that dosent work well.

    • http://blog.petersendidit.com/ David Petersen

      Something like this should work: http://jsfiddle.net/petersendidit/cZare/67/ Check out the new code / comment in droppable drop method.

  • B_hari50013

    Can I have a link for a downloadable working full example please!

  • Dhaval Shah

    Hi,
    I was trying to drag and drop the table rows from one table to another. I am able to achieve it but if i drag a row from one table to another, and if i drag and drop the same row back to the original table. it does not work.. any idea on this one?

  • shinde

    Hi this code was nice …..
    but I won’t to add that dragged value into gridview row.can you please tell me how can I do this…

  • shinde

    Hi
    Thanks alot for the demo but the it was not working after pageload ,how to do this

  • Chinmayee Misra

    This is not working in IE9 or OE10. is there any solution for IE9 And IE 10 too.

    • http://blog.petersendidit.com/ David Petersen

      If you update the versions of jQuery and jQuery UI in the demo link it seems to work fine in IE9 and 10. http://jsfiddle.net/petersendidit/cZare/146/show/

      • Chinmayee Misra

        Thanks alot for the demo it is working fine, can you help me for multiple selection , multiple Drag & Drop. Thanks in advance.

  • Lalitha

    Hi, How to make it work for touch devices as well ?

  • Swapnilraje Kumkar

    This is great.. :) I am trying to remove class from cart and back to table bt I am not able to.will u pls help me..

    Thanks in advance.. :)