0

I am working on this demo. I am researching how to use only call one time .droppable() with accept option for draggable elements to be accepted by dropping with specific ID. So:

dropboxt0 Accepts dragboxt0
dropboxt1 Accepts dragboxt1
dropboxt2 Accepts dragboxt2
dropboxt3 Accepts dragboxt3
dropboxt4 Accepts dragboxt4

I used following code

$(".dragbox").draggable();
$(".dropbox").droppable({
    accept:   $(this).attr('id'),
    drop: function (event, ui) {
        $(this)
            .addClass("ui-state-highlight")
            .html("Dropped!");
    }
});

but it is not doing the job.

halfer
  • 19,824
  • 17
  • 99
  • 186
Mona Coder
  • 6,212
  • 18
  • 66
  • 128

1 Answers1

0

The issue was already discussed over here: jquery droppable accept

instead of using a single selector for accept, you can use a function, that has to return true or false. inside the function, there are a lot of ways to get to your desired behaviour. i choose the following:

<div id="container">
    <div class="dropbox" data-drop-id="db01"></div>
    <div class="dropbox" data-drop-id="db02"></div>
    <div class="dropbox" data-drop-id="db03"></div>
    <div class="dropbox" data-drop-id="db04"></div>
    <div class="dragbox" data-drag-id="db01"></div>
    <div class="dragbox" data-drag-id="db02"></div>
    <div class="dragbox" data-drag-id="db03"></div>
    <div class="dragbox" data-drag-id="db04"></div>
</div>

js with the accept - function, to return true or false:

$(".dropbox").droppable({
accept: function (myDragBox) {
    var id_group_drop, id_group_drag;
    //get the "id_group" stored in a data-attribute of the draggable
    id_group_drag = $(myDragBox).attr("data-drag-id");
    //get the "id_group" stored in a data-attribute of the droppable
    id_group_drop = $(this).attr("data-drop-id");
    //compare the id_groups, return true if they match or false otherwise
    return id_group_drop == id_group_drag;
},
drop: function (event, ui) {
    $(this)
        .addClass("ui-state-highlight")
        .html("Dropped!");
}

});

important for my comparision is, that the id's of drop and dragbox are the same. therefore i didn't use the id attribute, but my own data-id attribute, since i like to have my id's being unique...

see demo here: http://jsfiddle.net/u9w63y2q/1/

Community
  • 1
  • 1
errand
  • 980
  • 1
  • 7
  • 18
  • don't forget to follow the stackoverflow link from my post and also honor the solutions of alex and morten, since all i did, was going into jquery api documentation - seeing, that "accept" also accepts a function and searched stackoverflow for this one ;) – errand Aug 27 '14 at 15:09