Jesper Pannerup
Jesper Pannerup

Reputation: 141

jQuery UI sortable and draggable. Getting the index of dragged element

I am having a very specific problem, using jQuery UI sortable and dragable together. I want to be able to get the index/placement in the list of the newly dragged element. I am able to get this if I move the elements around inside the list.

$("#draggable").draggable({
    cursor: "move",
    helper: "clone",
    connectToSortable: ".sortable"
});
$( ".sortable" ).sortable({
    items: 'li',
    stop: function(event, ui) {
        index = ui.item.index()+1;
        console.lo(index);
    },
    connectWith: ".sortableSub",
    appendTo: 'body',
}).disableSelection();

The code above works as it should, but if i do the same with the dragged element.

receive: function(event, ui) {
    console.log(ui.item.index());
},

using ui.item.index just returns 0, if i do the same in stop: instead of receive: it returns -1 instead, and this is no matter where it is dropped.

Upvotes: 0

Views: 8879

Answers (3)

Here is the solution to get dragged item in ui.sortable.

On Receive function, Use **ui.item.sortable.model** to get the dragged object.

receive: function(event, ui) 
{
   console.log("Task No : " + ui.item.sortable.model.SID);
},

NOTE: My object has a property named SID.

Upvotes: 0

Tonda Krist
Tonda Krist

Reputation: 209

here is the solution how to get the index of ADDED item in sortable list.

receive: function( event, ui ) {
  var newIndex = $(this).data("ui-sortable").currentItem.index()
}

Upvotes: 3

sangram parmar
sangram parmar

Reputation: 8736

Try this:

$("#draggable").draggable({
    cursor: "move",
    helper: "clone",
    connectToSortable: ".sortable"
});
$( ".sortable" ).sortable({
    items: 'li',
    stop: function(event, ui) {
        index = ui.item.index()+1;
        console.log(index);
    },
    connectWith: ".sortableSub",
    appendTo: 'body',
}).disableSelection();

$( "#draggable" ).on( "dragcreate", function( event, ui ) {

  console.log(ui.item.index());
});

or try this:

$("#draggable").draggable({
    cursor: "move",
    helper: "clone",
    connectToSortable: ".sortable",
    create: function( event, ui ) {
        var index = ui.item.index()+1;
         console.log(index);
    }
});
$( ".sortable" ).sortable({
    items: 'li',
    stop: function(event, ui) {
        index = ui.item.index()+1;
        console.log(index);
    },
    connectWith: ".sortableSub",
    appendTo: 'body',
}).disableSelection();

Upvotes: 1

Related Questions