I have a list generated with json, and it's sortable with RubaXa/Sortable plugin. I need to add the item position in the list while sorting the list. So when moving an item up or down the item position indicators will change. I commented some lines with the issue.
Sortable function:
var listPos;
Sortable.create(list-group, {
handle: '.driver',
animation: 150,
onMove: function (evt) {
evt.dragged;
evt.draggedRect;
evt.related;
evt.relatedRect;
listPos = $(this).closest('.list-group').children('.list-group-item').index(this); // error finding the position in the list
console.log(evt); // event is shown in the console
console.log(listPos); // this is showing always -1 after the event
}
});
The json:
[
{
"name": "item 1",
"acr": "it1"
},
{
"name": "item 2",
"acr": "it2"
},
{
"name": "item 3",
"acr": "it3"
},
{
"name": "item 4",
"acr": "it4"
}
]
The HTML:
<div class="col-md-4">
<div id="printList" class="list-group">
</div>
</div>
Parsing/Printing the json:
var xmlhttp = new XMLHttpRequest();
var url = "/list.json";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
showListPos = listPos; // showListPost in undefined
var arr = JSON.parse(response);
var i;
var out = "";
var drawPos = "<div class='position'>" + showListPos + "</div>"; //
for (i = 0; i < arr.length; i++) {
out += "<div class='list-group-item'>" +
"<p>" + drawPos + "</p>"
"<h3><span>" + arr[i].name + "</span>" +
arr[i].acr +
"</h3></div>";
}
out += "";
document.getElementById("printList").innerHTML = out;
}
to get the moved item position while moving it,you can use
onEnd
event insteadonMove
.inonEnd
you can access position usingevt.newIndex
.check the below snippet