limeygent limeygent - 3 months ago 13
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

<div>
).

The
$('.box-item').each(function()...
piece of code always runs one time more than the total number of items with class of
.box-item
.

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
    mainContainer
    )

  3. click on "add group"

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



Here is the jQuery code:

$("[id^=container]").droppable({
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);

q++;
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();
console.log(txt);
var abc = $(this).closest(".box-container").attr("id");
console.log ("to: " + abc);
}
});
}
});

Answer

Just change your selector like:

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

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