Alan
Alan

Reputation: 279

JQuery droppable, when list item is dropped, unable to get 'id' attribute using attr()

My problem is similar to the below link

How to get the dropped item's id on drop event jquery

However I am dragging and dropping a list item, each contain images.

When the list item is dropped, I need to get the 'id' attribute, which will then be passed to php on 'submit', to update the database.

But the below code does not seem to be capturing the 'id' attribute or if i try 'src', I have amended the following

$("#drop").text(id); to $("#drop").text("image has been dropped");

which does display correctly, "image has been dropped" upon a drop event, so the problem seems to be with getting the 'id' attribute within a list item? I tried adding a class called 'image' to use instead of the list item, tried many things, but makes no difference!

Hope someone can point me in the right direction!

Thanks

below is my code

JQuery

$(document).ready(function() {

    $("#item-slider li").draggable({
        containment: 'document',
        revert: true,
        helper: "clone",
        cursor: "move"
    });


    $("#drop").droppable({
        accept: "#item-slider li",
        drop: function (event, ui){
            var draggable = ui.draggable;
            var id = draggable.attr("id");
            $("#drop").text(id);
        }
    });

});

Html

<div id="item-slider">
<ul>
    <li class='image'><img src="./images/jeans1.jpeg" id="jeans1.jpeg" /></li>
    <li class='image'><img src="./images/top2.jpg" id="top2.jpg" /></li>
    <li class='image'><img src="./images/top1.jpg" id="top1.jpg" /></li>
    <li class='image'><img src="./images/shoes3.jpg" id="shoes3.jpg" /></li>
    <li class='image'><img src="./images/dress1.jpg" id="dress1.jpg" /></li>
</ul>

<div id="drop">
</div>
</div>

Upvotes: 2

Views: 2962

Answers (1)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262919

The id attributes you're looking for do not belong to your <div> elements, but to their <img> children. You can match these elements with find() or children():

drop: function(event, ui) {
    var id = ui.draggable.find("img").attr("id");
    $("#drop").text(id);
}

Upvotes: 2

Related Questions