user3464872
user3464872

Reputation: 21

only allow one object to be dropped jquery

$("li").draggable({
            helper: "clone"
        });

        $("#div1").droppable({
            drop: function (event, ui) {
                $("<p></p>").appendTo("#div1");

            }
        });

I have objects in a list that can be dragged and dropped into a div named div1. But when I drop one into the div i don't want to be able to drop another into it. I have tried using, for, if and while loops with a count.

Upvotes: 1

Views: 1305

Answers (2)

Damon Hogan
Damon Hogan

Reputation: 552

Here is a full solution, it allows only one item dropped, but also, if one exists, it gets replaced on the next drop with the new one. (Usefull if someone changes their mind. Just call

refreshDragDrop(dragClassName,dropDivId); 

refreshDragDrop = function(dragClassName,dropDivId) {
  $( "." + dragClassName ).draggable({
    connectToSortable: "#" + dropDivId,
    helper: "clone",
    revert: "invalid"
  });
  $("#" + dropDivId).droppable({
    accept: '.' + dragClassName,
    drop: function (event, ui) {
      var $this = $(this),
        maxItemsCount = 1;
      if ($this.children('div').length == maxItemsCount ){
        //more than one item,just replace
        $(this).html($(ui.draggable).clone());
      } else {
        $(this).append($(ui.draggable).clone());
      }
    }
  });
}

Upvotes: 1

Marcin Cichocki
Marcin Cichocki

Reputation: 1

This should help:

drop: function (event, ui) {
    var $this = $(this),
    maxItemsCount = 1;

    if ($this.children('li').length > maxItemsCount ){
        ui.sender.draggable('cancel');
        alert("To much items!");                
    }    

}

Upvotes: 0

Related Questions