Search code examples
javascriptjqueryjquery-ui-draggablejquery-ui-droppable

Jquery disable a droppable after it has reached a limit of 3 elements


I have two list boxes that drag and drop I want my second list box to only allow 3 list items from the first list box. My problem is that when I reach the limit it does the counter works but I get this error:

Uncaught Error: cannot call methods on draggable prior to initialization; attempted to call method 'disable'

and it allows it to drag more than 3 elements. I would like it to stop at 3 elements and when I drag out from the second list box it minus the counter.

var counter = 0;

$("#listbox2").droppable({
    drop: function(event, ui) {
        if (counter <= 3) {
            counter++;
            $('#counter_text').text(counter);
        }
        if (counter === 3) {
            $('#listbox2').droppable("disable");
            $('#listbox1 li').draggable("disable");
        }
    }
})

$("#listbox1").droppable({
    drop: function(event, ui) {
        counter--;
        $('#counter_text').text(counter);

    }
})

Solution

  • Yu simply have to initialize the draggable elements. This is a working sample (with an awful styling, BTW)

    var counter = 0;
    $('#counter_text').text(counter);    
    
    $('#listbox1 li').draggable({
      stop: function(event, ui) {
        $(this).css('left',0);
        $(this).css('top',0);
      }
    });
    
    $("#listbox2").droppable({
      drop: function(event, ui) {
        $(this).append(ui.draggable);
        if (counter <= 3) {
          counter++;
          $('#counter_text').text(counter);
        }
        if (counter === 3) {
          $('#listbox2').droppable("disable");
          $('#listbox1 li').draggable("disable");
        }
      },
      hoverClass: 'hover'
    });
    
    $("#listbox1").droppable({
      drop: function(event, ui) {
        counter--;
        if (counter<3) {
          $("li").draggable("enable");  
          $('#listbox2').droppable("enable");
        }
        $('#counter_text').text(counter);    
        $(this).append(ui.draggable);
        $(ui.draggable).draggable('enable');
      },
      hoverClass: 'hover'
    });
    ul {
      border: solid 1px green;
      padding: 5px;
      height: 120px;
    }
    
    .hover {
      background-color: #CFC;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
    
    <div id="counter_text"></div>
    
    <ul id="listbox1">
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
      <li>Item 4</li>
      <li>Item 5</li>
    </ul>
    
    <ul id="listbox2">
    </ul>