Search code examples
javascriptjqueryjquery-uidraggabledroppable

Adding tags to draggable and droppable items after drop


I have an unordered list in one div and I want to achieve that when I drag and drop any of these list items into another div element, I want a new div to be created inside an old div with this list item inside, so that I could add new tags in these new divs. I am using JQuery draggable and droppable widget. How can I do this?

Here is my script:

<script type="text/javascript">
    $(document).ready(function(){
        $('#source li').draggable({
            helper: 'clone',
            revert: 'invalid'
        });
        $('#divCountries').droppable({
            accept : 'li[data-value="country"]',
            drop : function(event, ui){
                $(this).append(ui.draggable);
                return '<div>' + $(this).text() + '</div>'
            },
        });
        $('#divCities').droppable({
            accept : 'li[data-value="city"]',
            drop : function(event, ui){
                $(this).append(ui.draggable);
                return '<div>' + $(this).text() + '</div>'
            },
        });
    });
</script>

And this is my body tag:

<body style="font-family: Arial">
<form id="form1" runat="server">
    <div class="divClass">
        Countries & Cities
        <ul id="source">
            <li data-value="country">USA</li>
            <li data-value="country">Germany</li>
            <li data-value="country">UK</li>
            <li data-value="city">New York</li>
            <li data-value="city">Berlin</li>
            <li data-value="city">London</li>
        </ul>
    </div>
    <div class="divClass" id="divCountries">
        Countries

    </div>
    <div class="divClass" id="divCities">
        Cities

    </div>
</form>


Solution

  • My guess is that you will need to edit the ui.draggable element.

    Something like

    var item = $(ui.draggable).data('test', 1);
    $(this).append(item);
    

    in the drop function. That will attach data to the element. You could also wrap it in a div which you manually create to attach the elements to instead.

    var item = $('<div data-test="foo">').append(ui.draggable); 
    $(this).append(item);