So I am trying to implement a sortable list. But, the list is generated using JavaScript from an array. This array comes from back-end c#.
Here's my Sortable jquery -
$('.sortable-list').sortable({
connectWith: '.sortable-list',
update: function (event, ui) {
var changedList = this.id;
var order = $(this).sortable('toArray');
var positions = order.join(';');
success: writeCategories(positions);
console.log("positions written");
},
});
And here's my JavaScript function that generates a list ...
function makecategories(array) {
// Create the list element:
var list = document.createElement('ul');
list.id = "boo";
list.className = "sortable-list ui-sortable";
for (var i = 0; i < array.length; i++) {
// Create the list item:
var item = document.createElement('li');
item.id = i + 1;
item.className = "ui-sortable-handle";
item.style = '"margin: 1px; width: 130px; padding: 2px; vertical - align: middle;"';
// Set its contents:
item.appendChild(document.createTextNode(array[i]));
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
Here's how I get my array from backend and call my JS fucntion
var categories = <%= this.javaSerial.Serialize(this.Menus) %>;
//alert(categories[3]);
document.getElementById('categories').appendChild(makecategories(categories));
This is my HTML
<div id="categories">
</div>
This is the result I get -
Hen
Dog
Cat
But this list is not sortable. Any help here would be greatly appreciated.
Here's something I tried-
<div id="categories">
<ul class="sortable-list">
<li id="1"> Food </li>
<li id="2"> Drinks </li>
</ul>
<div>
This gives me a result of-
Food
Drinks
Hen
Dog
Cat
Out of this the food and drinks list is sortable and the hen dog cat list is not sortable.
Please feel free to ask me any more info that maybe required.
Consider thew following example.
$(function() {
function makeSortList(arr, obj) {
if (obj == undefined) {
obj = "body";
}
obj = $(obj);
var list = $("<ul>", {
id: "boo",
class: "sortable-list"
});
$.each(arr, function(i, v) {
$("<li>", {
id: i + 1
}).html(v).css({
margin: "1px",
width: "130px",
padding: "2px",
verticalAlign: "middle"
}).appendTo(list);
});
list.appendTo(obj).sortable({
connectWith: '.sortable-list',
update: function(e, ui) {
var changedList = $(this).attr("id");
var order = $(this).sortable('toArray');
var positions = order.join(';');
//success: writeCategories(positions);
console.log("positions written", positions);
}
});
return list;
}
makeSortList(["Cat 1", "Cat 2", "Cat 3"], "#categories");
});
.sortable-list {
list-style-type: none;
margin: 0;
padding: 0;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id="categories"></div>
You can see this creates the List from Array items and then initializes Sortable once it has been appended.