Helper function in jQuery - drag & drop

I am trying to write a helper function for jQueryUI to set the attribute of an item being dragged from a draggable list to a sortable list. (The reason I need to do this is because the latest jQueryUI version removes the id attribute of the discarded elements)

However, the attribute does not fall into the sortable list. Am I doing something wrong in a helper function?

 $("#draggable > li").draggable({ connectToSortable: "#sortable", helper: function (event) { var id = $(this).attr('id'); var ret = $(this).clone(); ret.attr('dragId', id); console.log('dragId: ', ret.attr('dragId')); return ret(); } }); $( "#sortable" ).sortable({ start: function( event, ui ) { console.log( "sortable start: dragId=", ui.item.attr( "dragId" ) ); }, stop: function( event, ui ) { console.log( "sortable stop: dragId=", ui.item.attr( "dragId" ) ); } }); 

When I drag an item from a drag list to a sorted list, it prints to the console:

 dragId: itemA sortable start: dragId= undefined sortable stop: dragId= undefined 

I expect it to print:

 dragId: itemA sortable start: dragId= itemA sortable stop: dragId= itemA 

Here is a complete example (with HTML) on JsBin

+6
source share
2 answers

You set the dragId attribute on the helper element, so ui.item should be used ui.helper :

 console.log("sortable start: dragId=", ui.helper.attr("dragId")); 

EDIT: Nicola Peluchetti is right in his comment below: ui.helper will indeed be null during the stop event. Since you probably want to use the dragId attribute during this event, a workaround would be to copy the attribute during the start event when both ui.helper and ui.item :

 $("#sortable").sortable({ start: function(event, ui) { ui.item.attr("dragId", ui.helper.attr("dragId")); console.log("sortable start: dragId=", ui.item.attr("dragId")); }, stop: function(event, ui) { console.log("sortable stop: dragId=", ui.item.attr("dragId")); } }); 
+5
source

The only way to save the id found is to add droppable and this code:

  $( "#sortable" ).droppable({ drop: function( event, ui ) { $(ui.draggable).attr('id', $(ui.helper).attr('id')); } }); 

There is a fiddle here (and there should be a better way to do this) http://jsfiddle.net/MdZwB/1/

+1
source

Source: https://habr.com/ru/post/893097/


All Articles