22

Here is an interesting use of JavaScript: reordering items with drag and drop. The implementation itself in my page works fine, but is there a way to determine in which order the user put the items?

I'm asking because I want to load and save the item order in a cookie.

5 Answers 5

46

UPDATED 2012

FULL WORKING DEMO & SOURCE


get the index position of the elements try to read this:

COOKIE plugin for jquery:

JQUERY:

 $(function() {
    //coockie name
     var LI_POSITION = 'li_position';
       $('ul#sortable').sortable({
         //observe the update event...
            update: function(event, ui) {
              //create the array that hold the positions...
              var order = []; 
                //loop trought each li...
               $('#sortable li').each( function(e) {

               //add each li position to the array...     
               // the +1 is for make it start from 1 instead of 0
              order.push( $(this).attr('id')  + '=' + ( $(this).index() + 1 ) );
              });
              // join the array as single variable...
              var positions = order.join(';')
               //use the variable as you need!
              alert( positions );
             // $.cookie( LI_POSITION , positions , { expires: 10 });
            }
        });
     });​

HTML:

<ul id="sortable"> 
  <li id="id_1"> Item 1 </li> 
  <li id="id_2"> Item 2 </li> 
  <li id="id_3"> Item 3 </li> 
  <li id="id_4"> Item 4 </li> 
  <li id="id_5"> Item 5 </li> 
</ul>

PHP:

this is just an example but you got the idea: you may want use a database instead and use AJAX for get back the lis:

<?php  
//check if cookie is set..
if ( isset( $_COOKIE['li_position'] ) ) {
//explode the cockie by ";"...
$lis = explode( ';' , $_COOKIE['li_position'] );
// loop for each "id_#=#" ...
foreach ( $lis as $key => $val ) {
//explode each value found by "="...
$pos = explode( '=' , $val );
//format the result into li...
$li .= '<li id="'.$pos[0].'" >'.$pos[1].'</li>';
}
//display it
echo $li;
// use this for delete the cookie!
// setcookie( 'li_position' , null );
} else {
// no cookie available display default set of lis
 echo '
  <li id="id_1"> Fuji </li> 
  <li id="id_2"> Golden </li> 
  <li id="id_3"> Gala </li> 
  <li id="id_4"> William </li> 
  <li id="id_5"> Jordan </li> 
';
}
?>
4
  • You bring up an interesting Stack Overflow thread. I think the serialize method might get me to where I need to go, but I can't quite put the pieces together.
    – Pieter
    Apr 19, 2010 at 17:30
  • Great! That leaves one final question: how do I make the li's appear in the correct order when I reload the page? Can I retrieve this cookie with PHP?
    – Pieter
    Apr 22, 2010 at 11:13
  • Also, I get a weird error message from Google Chrome. It works fine in Internet Explorer. (path goes here...)/jquery.cookie.js:80 Uncaught Error: SECURITY_ERR: DOM Exception 18
    – Pieter
    Apr 23, 2010 at 9:40
  • Demo source link is broken. Sep 25, 2022 at 12:25
40

Use toArray method which serializes the sortable's item id's into an array of string.

$( "#sortable" ).sortable('toArray');
3
  • 1
    returns an array of id attributes in the sorted order.
    – logic8
    Nov 24, 2013 at 5:29
  • 3
    Simple and effective, the way I like it. This should be the accepted answer.
    – kramer65
    Nov 8, 2014 at 10:13
  • 4
    $( "#sortable" ).sortable( "toArray", {attribute: "data-some-attribute"}) if you prefer to avoid id. Dec 7, 2015 at 18:53
7

HTML

<ul id="sortable"> 
  <li id="id1"> Item 1 </li> 
  <li id="id2"> Item 2 </li> 
  <li id="id3"> Item 3 </li> 
  <li id="id4"> Item 4 </li> 
  <li id="id5"> Item 5 </li> 
</ul>

JQUERY

 $("#sortable").sortable(
            {
                update: function () {
                var strItems = "";

                $("#sortable").children().each(function (i) {
                    var li = $(this);
                    strItems += li.attr("id") + ':' + i + ',';
                });

                updateSortOrderJS(strItems); <--- do something with this data

                }
            });

strItems will look like (new-item-order:item-id)

0,49:1,365:2,50:3,364:4,366:5,39:6

then you can parse it into an update functions something like

List eachTask = new List(itemsList.Trim().Split(new char[] { ',' }));

then

String[] item = i.Split(new Char[] { ':' });

1

This is what I use currently:

<div id="sortable">
    <div id="2000"></div>
    <div id="1000"></div>
    <div id="3000"></div>
</div>

$('#sortable').sortable({
    update: function () { save_new_order() }
});

function save_new_order() {
    var a = [];
    $('#sortable').children().each(function (i) {
        a.push($(this).attr('id') + ':' + i);
    });
    var s = a.join(',');
    alert(s);
}

Alerted value:

2000:0,1000:1,3000:2
0

I have used following code to get the order of item.

Html

     <div id="sortable">
        <div >1</div>
        <div >2</div>
        <div >3</div>
        <div >4</div>
        <div >5</div>
        <div >6</div>
        </div>

JQuery

     $(document).ready(function(){
        $("#sortable").sortable({
            stop : function(event, ui){
        $('#sortable > div').each(function(){
           alert($(this).html());
       });          
        }
    });
  $("#sortable").disableSelection();
});

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.