limeygent limeygent - 2 months ago 4x
Javascript Question

jquery droppable: class.each cycles once more than the number of classed elements

Refer to jsfiddle

I am using jQuery to move items between elements. Once the item is dropped onto the new element, I want to pull out the text of the item (it's inside a


piece of code always runs one time more than the total number of items with class of

How do I capture the text from the item that is being dropped only once?

How to test (refer to jsfiddle)

  1. Enter 4 items into the textarea (new line between each one): A, B,
    C, D

  2. Click on "populate" (the items are created in

  3. click on "add group"

  4. Drag items from
    over to one of the containers on the right

Here is the jQuery code:

drop: function(event, ui) {
var elemId = $(this).attr("id");
var itemid = $(event.originalEvent.toElement).attr("itemid");
var q = 1;
$('.box-item').each(function() {
// this section always runs one more time than the number of items
console.log (q);
var aaa= $(this).closest(".box-container").attr("id");
console.log ("parent div: " + aaa);

if ($(this).attr("itemid") === itemid) {
// this section gets executed twice
var abc = $(this).closest(".box-container").attr("id");
console.log ("from: " + abc);
console.log ("append2:" + "<div id='" + elemId + "'>" );
$(this).appendTo("#" + elemId);

// what is in the div?
var txt = $(this).text();
var abc = $(this).closest(".box-container").attr("id");
console.log ("to: " + abc);


Just change your selector like:

$('.box-item:not(.ui-draggable-dragging)').each(function() {

and it works. The draggable clone's class is also counted..