Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Sortable - Limit number of items in list

I have a schedule table I'm using jQuery Sortable for editing.

Each day is a UL, and each event is an LI.

My jQuery is:

    $("#colSun, #colMon, #colTue, #colWed, #colThu").sortable({
         connectWith: '.timePieces',
         items: 'li:not(.lith)'
    }).disableSelection();

To make all LI's sortable except those with class "lith" (day names). User can drag an event from day to day, or add new events by clicking a button, which appends a new draggable event (LI) to the fist UL (Sunday).

I want to make each day accept only up to 10 events. How do I do this?

like image 825
Adam Tal Avatar asked Mar 13 '10 13:03

Adam Tal


2 Answers

  • DEMO: http://so.lucafilosofi.com/jquery-sortable-limit-number-of-items-in-list
$(function() {
    $(".sortables").sortable({
        connectWith: '.connectedSortable',
        //receive: This event is triggered when a
        //connected sortable list has received an item from another list.
        receive: function(event, ui) {
            // so if > 10
            if ($(this).children().length > 10) {
                //ui.sender: will cancel the change.
                //Useful in the 'receive' callback.
                $(ui.sender).sortable('cancel');
            }
        }
    }).disableSelection();
});
like image 55
Luca Filosofi Avatar answered Sep 22 '22 04:09

Luca Filosofi


To have the function fire every time that you try to drag a new item into a specific list (dynamically) you need to use on() rather than the receive: method.

http://jqueryui.com/demos/sortable/#event-receive

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

    $( "#day1" ).on( "sortreceive", function(event, ui) {
        if($("#day1 li").length > 10){
            $(ui.sender).sortable('cancel');
        }
    });

});
like image 45
Spencer Avatar answered Sep 26 '22 04:09

Spencer