jqueryjquery-uijquery-ui-sortablejquery-droppable

maintaining counts of items in sortable lists


I need to maintain the exact counts of items in some sortable lists and am having trouble doing it. The moment I start dragging from list #1 that count increments and there is an extra item in play from then on. The moment I hover over list #2 it's count increments.

Example, click for fiddle:

$(function () {
    $("#ul1, #ul2").sortable({
        connectWith: ".connectedSortable"
    }).disableSelection();
  });

function update_counts() {
    var n_ul1 = $("#ul1 li").length;
    var n_ul2 = $("#ul2 li").length;
    $("#count1").html(n_ul1);
    $("#count2").html(n_ul2);
}

$(function () {
    $("#ul2,#ul1").droppable({
        over: function (ev, ui) {
            update_counts();
        },
        drop: function (ev, ui) {
            update_counts();
        }
    }).disableSelection();
});

Solution

  • I shall answer my own question:

    function update_counts() {
        var n_ul1 = $("#ul1 li").not(".ui-sortable-helper").length;
        var n_ul2 = $("#ul2 li").not(".ui-sortable-helper").length;
        $("#count1").html(n_ul1);
        $("#count2").html(n_ul2);
    }
    

    .not(".ui-sortable-helper") is what was needed.