0

I want to create a nested div with jquery-ui drag and drop plugin.
I create something like this but its not work for child1 and child2.
Fiddle Link

My code is like this:

$(function () {
    $('.parent,.child1,.child2').draggable({
        revert: true
    });
    $('.dest').droppable({
        accept: '.parent',
        drop: function (event, ui) {
            $('<div class="parent box"></div>').appendTo(this);
        }
    });
    $('.dest .parent').droppable({
        accept: '.child1',
        drop: function (event, ui) {
            $('<div class="child1 box"></div>').appendTo(this);
        }
    });
    $('.dest .parent .child1').droppable({
        accept: '.child2',
        drop: function (event, ui) {
            $('<div class="child2 box"></div>').appendTo(this);
        }
    });
});

1 Answer 1

3

It doesn't work because on document ready, $('.dest .parent') and $('.dest .parent .child1') don't match anything, so droppables are not initialized for those selectors.

You have to initialize droppable when parent is dropped on .dest (and bind droppable only on the created .parent element)

$('.dest').droppable({
    accept: '.parent',
    drop: function (event, ui) {
        $newElt = $('<div class="parent box"></div>');
        $newElt.appendTo(this);
        $newElt.droppable({...});
    }
});  

I edited your fiddle:

You can see the full demo here

EDIT:

If you want to check if only one .child2 exists when dropping on .child1, you can put your .append() inside an if/else structure, and use the .find() function, combined to length (which retrieve the number of element found):

if($(this).find('.child2').length < 1){ //Check if the number of existing .child2 in this .child1 is inferior to 1
    //do your append here
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks. one little question. how can I check that only one child2 exist inside child1?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.