gautamlakum
gautamlakum

Reputation: 12015

jquery droppable based on condition

Below is my code.

$(document).ready(function(){
    $("#container li").draggable({ revert: 'invalid' });
    var total = 0;
    $("#selected ul").droppable({
        drop: function(e, ui) {
            $(ui.draggable).css({ top: 0, left:  0 }).appendTo(this);
        },
        accept: function() {
            return $("#selected li").length < 5;
        },
        placeholder: true
    });
    $("#container ul").droppable({
        drop: function(e, ui) {
            $(ui.draggable).css({ top: 0, left:  0 }).appendTo(this);
        },
        placeholder: true
    });
});

It is something like we can drag and drop LI elements from container div to selected div and vice versa. Everything is working, but LI elements that are dragged and dropped are not being sorted. I mean, if I drop an LI element from container to selected, it is always moved to at the end of LI list. Same happens when I drop element from selected to container div.

So what should I do to make LI sortable?

Here is link: http://www.jsfiddle.net/nick_craver/HemSU/1/

Please need help to resolve this out. Thanks.

Upvotes: 1

Views: 1433

Answers (2)

Nick Craver
Nick Craver

Reputation: 630429

For what you're after (very different from the original question), .sortable() would be more appropriate, like this:

$(document).ready(function(){
    function checkMax() {
        var max = $("#selected li").length >= 5;
        $("#container ul").sortable("option", { 
            revert: max, connectWith: max ? '' : '#selected ul'
        });
    }
    $("#selected ul").sortable({
        connectWith: '#container ul',
        receive: checkMax
    }).disableSelection();
    $("#container ul").sortable({
        connectWith: '#selected ul',
        receive: checkMax
    }).disableSelection();
});

You can test it out here.

Upvotes: 2

David M&#229;rtensson
David M&#229;rtensson

Reputation: 7600

Well you append to the UL, that means it will end up last.

If you want to be able to insert it in a specific place in the list you should probably have the LIs as droppable, not the UL.

And then user insertbefore that LI instead of append to.

Upvotes: 1

Related Questions