Search code examples
javascriptdatatableshtml-listsdragdrop

Drag a row from a jquery datatable to an unordered list


I'm trying to drag a row from a datatable to an li or ul element. e.g.

enter image description here

The rows have the draggable and ondragstart attribute in them e.g.

<tr class="even" role="row" style="height: 22px;" draggable="true" ondragstart="drag(event)" }="">
    <td class="sorting_1" style="display: none;">
        <input name="item.ID" id="item_ID" type="hidden" value="30">
    </td>
    <td> Menu Structure </td>
    <td> IdentityComponent </td> ..etc                          
</tr>

The markup in the UL, allowing it as a target for a drop :

<li>
<span class="accordion-heading" aria-expanded="false" data-toggle="collapse" data-target="#MMID_0">
    <input name="MM_0" class="mmTree-cnode hidden" id="MM_0" type="input"  iid="FkComponentId=ComponentId=29 |"/> &nbsp; 
<span class="glyphicon glyphicon-plus"></span> &nbsp;
<span class="componentName" ondragover="allowDrop(event)" ondrop="drop(event)"> &nbsp;  
       Administration
</span>
</span>
<ul>
    <li>..blah blah<li/>
    <li>..blah blah<li/>
</ul>

It looks like the drag portion works, but on dropping I get this error, re the 'data' parameter (in the drop function), at this line. (data = ""). Possibly the 'dataType as text is incorrect??

ev.target.appendChild(document.getElementById(data));

Unhandled exception at line 1923, column 3 in http://localhost:60667/IdentityComponentPermission/List
0x80070057 - JavaScript runtime error: Invalid argument.

Thanks


Solution

  • The drag function changed from the W3 schools example, to

    function drag(ev)
    {
        ev.dataTransfer.setData("text", ev.target.innerText);
    
        console.log("Target  innerText = " + ev.target.innerText);
        console.log("Cells innerHTML for the ID = " + ev.target.cells[0].innerHTML);
        console.log("Target  innerHTML = " +ev.target.innerHTML);
    }
    

    and the drop to

    var srcData = ev.dataTransfer.getData('text');
    

    // srcData now has the value 'Countries Country List' , i.e. the innerText

    // passing the ev.target.cells[0].innerHTML, gives me

    <input name="item.ID" id="item_ID" type="hidden" value="33">
    

    // passing the ev.target.innerHTML, gives me the entire row's markup

    From here it is a matter of extracting what I want, or iterating the cells of the entire row into an array (possibly in a form scope variable) and retrieving it in the drop function and appending what I want from that, to a UL or Li .