Updating sort order during sort change event - jQuery UI

I want the value of the list item to be the index of the sorted position during the sorting event.

This value should be updated automatically during the sort change event.

<script type="text/javascript"> $(function() { $('#sortable').sortable({ start : function(event, ui) { var start_pos = ui.item.index(); ui.item.data('start_pos', start_pos); }, change : function(event, ui) { var start_pos = ui.item.data('start_pos'); var index = ui.placeholder.index(); if (start_pos < index) { $('#sortable li:nth-child(' + index + ')').html(index-2); } else { $('#sortable li:eq(' + (index + 1) + ')').html(index + 1); } }, update : function(event, ui) { var index = ui.item.index(); $('#sortable li:nth-child(' + (index + 1) + ')').html(index); }, axis : 'y' }); }); </script> 

I created a fiddle http://jsfiddle.net/jagan2explore/4mcpq/

to explain my requirement.

If I move the 1st element to the 5th position, all other values ​​of the elements are updated correctly, If I move the 5th and 1st values, respectively.

Suppose if I move a list item from 1 to 5 and from 5 to 2 without leaving (during a single sort event) the values ​​are not updated accordingly.

Am I missing something ??

Any help would be greatly appreciated. thanks in advance

+4
source share
2 answers

Try the following:

 update : function(event, ui) { var index = ui.item.index(); var start_pos = ui.item.data('start_pos'); //update the html of the moved item to the current index $('#sortable li:nth-child(' + (index + 1) + ')').html(index); if (start_pos < index) { //update the items before the re-ordered item for(var i=index; i > 0; i--){ $('#sortable li:nth-child(' + i + ')').html(i - 1); } }else { //update the items after the re-ordered item for(var i=index+2;i <= $("#sortable li").length; i++){ $('#sortable li:nth-child(' + i + ')').html(i-1); } } }, 

Demo: jsfiddle

+12
source

I updated your fiddle with a different approach, it seems to work as expected:

  $(function() { $('#sortable').sortable({ start : function(event, ui) { var start_pos = ui.item.index(); ui.item.data('start_pos', start_pos); }, change : function(event, ui) { var start_pos = ui.item.data('start_pos'); var index = ui.placeholder.index(); cIndex = (start_pos < index) ? index-2 : index-1; ui.placeholder.prevAll('li').each(function(){ $this = $(this); if($this.is(ui.item)) {return;} $this.html(cIndex); cIndex--; }); cIndex = (start_pos < index) ? index : index+1; ui.placeholder.nextAll('li').each(function(){ $this = $(this); if($this.is(ui.item)) return; $this.html(cIndex) cIndex++; }); ui.item.html((start_pos < index) ? index-1 : index); }, axis : 'y' }); }); 

Demo Here is the violin!

+1
source

All Articles