NZLearner NZLearner - 1 month ago 10
Javascript Question

jquery droppable and draggable not working on dynamically created tables in for loop

I am trying to make tables dynamically created in a for loop draggable and droppable. It is not working. For static table it works fine. Fiddle here

Javascript:

$(document).ready(function () {
$("#button1").click(function () {
for (var j = 1; j < 4; j++) {
var table = document.createElement("table");
var tbody = document.createElement("tbody");
for (var i = 1; i < 5; i++) {
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");

var text1 = document.createTextNode("Text" + j + "-" + 1 + i);
var text2 = document.createTextNode("Text" + j + "-" + 2 + i);

td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);

tr.appendChild(td2);

tbody.appendChild(tr);
table.appendChild(tbody);

//var id = "a" + j + "." + i;
//tr.attr({"id",id}).appendTo(table);
// tr.setAttribute("id", id);
}

document.getElementById("tb").appendChild(table);
table.setAttribute("id", "t" + j);
tbody.setAttribute("id", "tb" + j);
$("#" + "tb" + j).sortable({
items: "> tr:not(:first)",
appendTo: "parent",
helper: "clone"
}).disableSelection();
}
});
});


HTML:

<button id="button1">
button1
</button>
<div id="tb">
</div>

Answer

Add jQuery UI library to your project after jQuery:

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

After that, your code works fine. Here is a JS Bin.