Reputation: 446
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;
}
Upvotes: 0
Views: 798
Reputation: 3202
to get the moved item position while moving it,you can use onEnd
event instead onMove
.in onEnd
you can access position using evt.newIndex
.check the below snippet
Sortable.create(sortTrue, {
group: "sorting",
sort: true,
onEnd: function(evt) {
$(evt.item).parent().find('.list-group-item').each(function() {
$(this).find('span').text($(this).index() + 1);
});
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="result">Drage the list item to see position</div>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<!-- Latest Sortable -->
<script src="http://rubaxa.github.io/Sortable/Sortable.js"></script>
<!-- sort: true -->
<div id="sortTrue" class="list-group">
<div class="list-group-item"><span>1</span> foo</div>
<div class="list-group-item"><span>2</span> bar</div>
<div class="list-group-item"><span>3</span> baz</div>
<div class="list-group-item"><span>4</span> qux</div>
<div class="list-group-item"><span>5</span> quux</div>
</div>
</body>
</html>
Upvotes: 1