Chaitanya
Chaitanya

Reputation: 37

How to get value of draggable element in jQuery?

I am using the jQuery to implement drag and drop. I want to get the value of the draggable control.

Draggable Control:
------------------

<li>@Html.Label(temp.Label, new { id = "droppable", style = "color:black; width:auto", value = temp.Key })</li>

Function to show draggable control value:
-----------------------------------------

     function initDroppable($elements) 
     {
            $elements.droppable({
                drop: function (event, ui) {
                    var tempid = ui.draggable;
                    var value = tempid.attr("value");
                    alert(value);
                }
            });
      }

Tried above code but the output is "undefined". I have tried various which doesn't seem to work. Any help is appreciated, Thanks!

Upvotes: 0

Views: 2933

Answers (2)

Twisty
Twisty

Reputation: 30899

Adding on to @Stuart, are we looking for input or label? Like this:

var tempid = $(ui.draggable).find("input");
var value = tempid.val();

I suspect the dragged item is something like:

<li>
  <label id="droppable" style="color:black; width:auto" value="1">Temp</label>
</li>

It would be helpful if you showed us e resulting HTML.

Also, why not use data attribute?

<li>
  <label id="droppable" style="color:black; width:auto" data-temp-key="1">Temp</label>
</li>

With:

var value = ui.draggable.data("temp-key");

Upvotes: 2

Stuart
Stuart

Reputation: 6780

Change:

var tempid = ui.draggable;

to:

var tempid = $(ui.draggable);

and then access the value via the attr method:

var value = tempid.attr("value");

Upvotes: 1

Related Questions