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

Check out the working demo



Comments

  1. Ariel Popovsky February 8, 2010
    9:51 pm

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


  2. mester April 27, 2010
    4:09 am

    good stuff!


  3. Rafeequ June 4, 2010
    2:39 am

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


  4. petersendidit June 4, 2010
    8:03 am

    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.


  5. Wepic July 6, 2010
    9:40 pm

    Good stuff, thanks for the tip!