How to get the dropped element in a jquery sortable list

180 views Asked by At

I have two unordered lists, and I want to be able to drag copies of any element in the first list, to a new second list. When the item is dropped, I want to access that element, in order to add it to a database etc.

I was expecting to be able to get to it using ui.item, but this is accessing the original item from the first list.

I don't want to access it in the stop or change function of the sortable, as I don't want it running my code if the list is reordered. I only want to run my code when the item is first dropped.

I either need to get the new element in stop or change and then pass the variable to the receive event, or I want to access it from there directly.

I have tried everything I know and cannot get to it.

$("#sortable").sortable({
  receive: function(event, ui) {
    // this is the original item, not the new clone.
    var thisItem = ui.item;
    thisItem.addClass("selected");
  },
  revert: true

});
$(".draggable").draggable({
  connectToSortable: "#sortable",
  helper: "clone",
  revert: "invalid"
});
$("ul, li").disableSelection();
#sortable { border: 1px solid green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js" ></script>

<style>
  .selected {
        border:5px solid red!important;
        background-color: aqua!important;
    }
</style>

<ul id="options">
  <li class="draggable">Option 1</li>
  <li class="draggable">Option 2</li>
</ul>

<ul id="sortable">
<li>Drag to here</li>
</ul>

1

There are 1 answers

1
AurelionZoul On

You can access it using ui.item just specify the ul id

Something like this:
$("#sortable li") this will give to array of sortable ul li

One more way is to create a hidden input field with the option added. By this on submit you will get all values of the hidden file and use it to save the value in DB.

<input type="hidden" name="selectedOption[0]" value="option1" />
<input type="hidden" name="selectedOption[1]" value="option1" />
<input type="hidden" name="selectedOption[2]" value="option1" />

You will get an selectedOption as array