Async list updates with jQuery sortable
The jQuery sortable is a nice jQuery plugin that allows easy drag/drop style of rearranging of lists.
http://jqueryui.com/demos/sortable/
I wanted the item to auto-update after index changed, but ran into issues on getting the new index
(e.g. moving “Item 1” under “Item 4” via a mouse click-and-drag)
<ul id="sortable">
<li id="1" class="ui-state-default">Item 1</li>
<li id="2" class="ui-state-default">Item 2</li>
<li id="3" class="ui-state-default">Item 3</li>
<li id="4" class="ui-state-default">Item 4</li>
<li id="5" class="ui-state-default">Item 5</li>
<li id="6" class="ui-state-default">Item 6</li>
<li id="7" class="ui-state-default">Item 7</li>
</ul>So I wrote this method to grab the new index during the update event for the sortable plugin<script>
$(function () {
$("#sortable").sortable({
update: function (event, ui) {
var indxSort = GetItemIndex(ui);//AJAX post to update new index of list (MVC Controller)
$.post("/list/reorderitem", { id: ui.item[0].id, index: indxSort });
}
});
});
function GetItemIndex(sender) {
var liElements = $("#sortable")[0].children;
var liElementsLength = $("#sortable")[0].children.length;
var index;
for (var i = 0; i < liElementsLength; i++) {
if (liElements[i].id == sender.item[0].id) {
index = i;
return index;
}
}
}
</script>The AJAX post in the above method will call an MVC Controller to update the list item’s index.public class ListController : Controller
{[HttpPost]
public ActionResult ReorderItem(string id, string index)
{//Update list item logic here
}}