Search code examples
asp.net-mvc-4jquery-uidrag-and-dropdraggabledroppable

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!


Solution

  • 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");