1

I'm using sortable for sorting a table. I would like to get the next or previous of the item that being sorted. Here's my code, a table with 4 rows and 2 columns for id and name:

<script type="text/javascript">
    $(document).ready(function(){
        $("#uat-item-grid .items tbody").sortable({
            stop: function(e, ui) {
                var itemId = ui.item[0].cells[0].outerText;
                console.log(itemId);
            }
        }).disableSelection();
    }
</script>
<div id="uat-item-grid">
<table class="items">
    <tbody class="ui-sortable">
        <tr class="even">
            <td>1</td>
            <td>Item 1</td>
        </tr>
        <tr class="odd">
            <td>2</td>
            <td>Item 2</td>
        </tr>
        <tr class="even">
            <td>3</td>
            <td>Item 3</td>
        </tr>
        <tr class="odd">
            <td>4</td>
            <td>Item 4</td>
        </tr>
    </tbody>
</table>
</div>

It will display the current id that being sorted in console. How can I get the previous or next item of the one being sorted, so I can get their ids? For example the one being sorted is 2, and the previous would be 1 and the next would be 3.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Henry Gunawan
  • 922
  • 3
  • 18
  • 38
  • Check out this anwer: [http://stackoverflow.com/questions/2850961/jquery-ui-sortable-get-the-item-being-sorted/2850992#2850992][1] [1]: http://stackoverflow.com/questions/2850961/jquery-ui-sortable-get-the-item-being-sorted/2850992#2850992 – derigible Oct 24 '13 at 20:21

1 Answers1

4

This will do the trick:

http://jsfiddle.net/Rusln/23gqU/

$("tbody").sortable({
    update:function(ev,ui){
        console.log(ui.item[0].nextElementSibling);
        console.log(ui.item[0].previousElementSibling);
    }
});
rusln
  • 1,284
  • 8
  • 10