Frage

Let me explain my situation: I've 3 positions where images can be hold. They don't have to be filled all.

Empty div | Img 1 | Img 2

When I change the Img 1 to the second place it would be:

Empty div | Img 2 | Img 1

Sortable works fine with this. But I want to save this to the database. The empty div has no ID or data which I want to use. I only want to use the Img's data. So the Img has a data-imgId attribute or something which I want to pass in an array with Javascript.

I want that in my array the "Current position" and the "Data-imgId" are added. Something like this:

Array
(
  [230] = 2
  [120] = 1
)

The 230 and 120 are the imageId's and the 2 and 1 are the sortId's. Now I just can update my database with the where clause on the imageId and then set the sortId on the good sort.

With the next code I can check the item which is moved, but the "automatically" moved other image is not returned. How can I fix this:

$( "#pages" ).sortable({
    helper: "clone",
    update: function(event, ui) {
        console.log($(ui.item).attr("id"));
        console.log($(ui.item).index() + 1);
    }
});

This code returns the id and the position of the dragged object. But I also want to retrieve the other auto moved image id and new position so I can use that for my Database?

War es hilfreich?

Lösung

Instead use sort(event, ui) which will give you additional information such as the new and original positions of the sorted item. You can then iterate over your array, reassigning position indexes based on these values.

http://api.jqueryui.com/sortable/#event-sort

UPDATE

Apologies, it seems the API no longer includes the before and after indexes. Instead you can use both the start(event, ui) and stop(event, ui) events, and record down the before and after indexes yourself using $(ui.item).index(). After you know these, you can then iterate over your original array, sorted by index position, and update the indexes accordingly.

UPDATE 2

Try this:

$("#pages").sortable({
    stop: function(event, ui) {
        $("#pages > img").each(function(i, item) {
            var id = $(this).attr("id");
            array[id] = i;
        });
    });
});

UPDATE 3

The following revision caters for multiple items, initialised by the classname sort.

var array = { One : {}, Two: {} };

$(".sort").sortable({
    stop: function(event, ui) {
        var id = $(this).attr("id");
        $(this).children().each(function(i, item) {
            var itemid = $(item).attr("id");
            array[id][itemid] = i;
        });
        console.log(array)
    }
});

See my fiddle.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top