pi-2r
pi-2r

Reputation: 1279

jQuery drag and drop - Allow only one item in list

I work with this example from jQuery UI Sortable

I have a problem with drag and drop.
Table number 3 - sortable3 should only be able to receive one item.

This is my HTML

<div class="demo">

<ul id="sortable1" class='droptrue'>
    <li class="ui-state-default">Can be dropped..</li>
    <li class="ui-state-default">..on an empty list</li>
    <li class="ui-state-default">Item 3</li>
    <li class="ui-state-default">Item 4</li>
    <li class="ui-state-default">Item 5</li>
</ul>

<ul id="sortable2" class='dropfalse'>
    <li class="ui-state-highlight">Cannot be dropped..</li>
    <li class="ui-state-highlight">..on an empty list</li>
    <li class="ui-state-highlight">Item 3</li>
    <li class="ui-state-highlight">Item 4</li>
    <li class="ui-state-highlight">Item 5</li>
</ul>

<ul id="sortable3" class='droptrue'>
</ul>

My CSS

#sortable1, #sortable2, #sortable3{
    list-style-type: none; 
    margin: 0; 
    padding: 0; 
    float: left; 
    margin-right: 10px; 
    background: #eee; 
    padding: 5px; 
    width: 143px;
}

#sortable1 li, #sortable2 li, #sortable3 li{
    margin: 5px; 
    padding: 5px; 
    font-size: 1.2em; 
    width: 120px; 
}

My Script

$(function() {
    $("ul.droptrue").sortable({
        connectWith: "ul"
    });

    $("ul.dropfalse").sortable({
        connectWith: "ul",
        dropOnEmpty: false
    });

    $("#sortable1, #sortable2, #sortable3").disableSelection();
});​

Upvotes: 3

Views: 6088

Answers (1)

Nope
Nope

Reputation: 22339

To prevent any additional items from being dropped into sortable3, cancel the drop if the maximum number has been exceeded.

The code below is your current code, I only added the last method which attaches the received event to the third sortable.

$(function() {
    $("ul.droptrue").sortable({
        connectWith: "ul",
    });

    $("ul.dropfalse").sortable({
        connectWith: "ul",
        dropOnEmpty: false
    });

    $("#sortable1, #sortable2, #sortable3").disableSelection();

    $("#sortable3").on("sortreceive", function(event, ui) {
        var $list = $(this);

        if ($list.children().length > 1) {
            $(ui.sender).sortable('cancel');
        }
    });
});​

DEMO

Upvotes: 1

Related Questions