jessier3
jessier3

Reputation: 849

jquery UI Draggable Sortable Looking for the Id of the dropped object

The big picture is I am looking to post all the elements dragged from one list and dropped into the sortable ul list. I want to be able to pull an element more than once and I want the list to be sortable and have the order come through in the form submission. If there is an easier way to do this I am totally open.

I am to the point where I am attempting to get the id of (or even better assign an id to) the dragged item and append an href to that item to remove it from the list if needed. However both the $(this) and the event.target are both targeting the sortable ul container rather than the li that was just dropped into it.

Once I can actually target that specific item I was going to throw open and close form tags inside the sortable ul and append hidden input fields to the lis as they are dragged across.

Question 1: How do I interact with the dropped li?
Question 2: Is there an easier way to do this?

HTML:

<ul id="draggable_list">
    <li id="1" class="draggable ui-state-highlight">Item 1</li>
    <li id="2" class="draggable ui-state-highlight">Item 2</li>
    <li id="3" class="draggable ui-state-highlight">Item 3</li>
    <li id="4" class="draggable ui-state-highlight">Item 4</li>
    <li id="5" class="draggable ui-state-highlight">Item 5</li>
</ul>

<ul id="sortable">

</ul>

JQuery:

<script type="text/javascript">
   $("#sortable").sortable({
        revert: true,
        stop: function(event, ui) {
            if(!ui.item.data('tag') && !ui.item.data('handle')) {
                ui.item.data('tag', true);
            }
        },
        receive: function (event, ui) {   
            $(this).append('<a href="" class="dragRemove">x</a>');
            alert($(event.target).attr('id'));
        }
}).droppable({ });
    $(".draggable").draggable({
        connectToSortable: '#sortable',
        helper: 'clone',
        revert: 'invalid'
    });

    $("ul, li").disableSelection();    

    </script>

Thank you!

Upvotes: 0

Views: 1949

Answers (1)

King King
King King

Reputation: 63377

You can access to the ui.item instead of e.target to get the id of the dropped item, however looks like you want to access to the cloned item, but jQuery does not provide any event so that we can listen to and access the cloned item via the event info argument. So we need to use a workaround here like in this code:

var currentChildren;
$("#sortable").sortable({
    revert: true,
    stop: function(event, ui) {
        if(!ui.item.data('tag') && !ui.item.data('handle')) {
            ui.item.data('tag', true);
        }
    },
    activate: function(event, ui){
       currentChildren = $(this).children();
    },    
    receive: function (event, ui) {          
        $(this).children().not(currentChildren)
               .append('<a href="" class="dragRemove">x</a>');            
    }
});

Demo.

Upvotes: 2

Related Questions