Ozgur Akcali
Ozgur Akcali

Reputation: 5492

jqueryui - Draggable loses id attribute when dragged to a sortable

I am using jqueryui's draggable and sortable functionalities. My jqueryui version is 1.9.1 and jquery version is 1.7.1

I have a set of items that I make draggable, and a container that is sortable. I drag the draggable items to the sortable container, and want to read the draggable item's id attribute in the sortable's stop handler. However, the id turns out to be undefiend there.

$(sortableselector).sortable({
    stop: function(event, ui) {
        alert(ui.item.attr('id'));
    }
});

$(draggableselector).draggable({
    revert: true,
    revertDuration: 0,
    connectToSortable: 'sortableselector',
});

prints undefined. I've seen several posts pointing this bug, but non has been resolved. How can I get the dragged item's id there?

Upvotes: 7

Views: 699

Answers (2)

Twisty
Twisty

Reputation: 30893

I tested with jQuery 1.7.1, using jQuery UI 1.9.1, and was able to replicate the issue with the snippet below. I am not able to replicate it the issue with modern versions. It looks like it was corrected some point in the last 11 years.

$(function() {
  $("#sortable").sortable({
    stop: function(event, ui) {
      console.log(ui.item);
    }
  });

  $("#draggable").draggable({
    revert: true,
    revertDuration: 0,
    connectToSortable: "#sortable",
  });
});
#sortable {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 60%;
}

#sortable li {
  margin: 0 3px 3px 3px;
  padding: 0.4em;
  padding-left: 1.5em;
  font-size: 1.4em;
  height: 18px;
}

#sortable li span {
  position: absolute;
  margin-left: -1.3em;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>

<ul id="sortable">
  <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li>
  <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li>
  <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 3</li>
  <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 4</li>
  <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 5</li>
</ul>
<div id="draggable" class="ui-widget-content">
  <p>Drag me around</p>
</div>

Upvotes: 0

spadelives
spadelives

Reputation: 1628

Try...

$(sortableselector).sortable({
stop: function(event, ui) {
    alert(ui.item[0].id);
}

});

Upvotes: -2

Related Questions