Question

Here's what I'm trying to achieve - I have seven list items within a sortable list (#sortable2) that I'm dragging and dropping into an empty sortable list (#sortable1).

I would like to count the number of elements that are in the new sortable list (#sortable1) and display an alert telling the user the current number of items. I would like this to work as an item is removed, too.

Here's my HTML:

    <ul id="sortable2" class="dropfalse">
       <li id="1">Section 1</li>
       <li id="2">Section 2</li>
       <li id="3">Section 3</li>
       <li id="4">Section 4</li>
       <li id="5">Section 5</li>
       <li id="6">Section 6</li>
       <li id="7">Section 7</li>
    </ul>

    <ul id="sortable1" class="droptrue">

</ul>

And jQuery:

    $("#sortable1 li").each(function() {
        var elem = $(this);

        // I have just added one example here (if two added) for brevity

        if (elem.children("li").length = 2) {
            alert('There are two elements');
        }
});
Was it helpful?

Solution

You'd need to run this on the drop event of the droppable - assuming jQueryUI droppable, something like this would work:

$('#sortable1').droppable({
    drop: function(event, ui) {
        var liCount = $("#sortable1 li").length;
        // do something with liCount...
    }
});

OTHER TIPS

The 2 main problems are:

using assignment instead of equation in when counting the number of elements

counting the children of the li element instead of the ul element the correct code:

$("#sortable1").each(function() {
        var elem = $(this);

        // I have just added one example here (if two added) for brevity

        if (elem.children("li").length == 2) {
            alert('There are two elements');
        }
});

You should use receive and remove events - as described in Sortable API.

Here's a working example in jsfiddle and here's example code:

function addRemoveHandler(event, ui) {
    alert("Number of items in sortable1: " + $(this).find("li").length);
}

$( "#sortable2" ).sortable({
    connectWith: "ul"
});
$( "#sortable1" ).sortable({
    connectWith: "ul",
    receive: addRemoveHandler,
    remove: addRemoveHandler
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top