Itsplanned.com is just launched! - Task and project management overview made easy. Go and try it for free.
Getting position from jQuery UI sortable
22.11.2009

The jQuery UI sortable widget offers a great interface for listing and moving element around.

I have been working on a small project of mine and figured that the sortable widget could be a great feature. I then started to output the list and the element that should be draggable like this:

My HTML list

<ul id="sort1">
  <li>
    <div>box no 1</div>
  </li>
  <li>
    <div>box no 2</div>
  </li>
  <li>
    <div>box no 3</div>
  </li>
</ul>

My jQuery code to enable the sortable widget and for getting a serialized result when an element has been dragged around:

$(document).ready(function() {
    $("#sort1").sortable({
        opacity: 0.6,
        update: function(event, ui) {
            var info = $(this).sortable("serialize");
            $("#sort1output").html(info);
        }

    });
});

Example (try dragging a box up or down):

  • box no 1
  • box no 2
  • box no 3

Serialized output (updated when a box is dragged):Output will be shown here

So. Nothing. No output what so ever.

I have spend several hour researching this problem, because the documentation on jqueryui.com lists that the serialize and toArray events should return output.

And then. Finaly. I stumpled upon a note regarding the id name of the element that gets dragged. I have seen no documentation about this and was quite puzzled. I digged some more into this id-hint and realized that the element that gets moved around, has to have a unique id tag ending with a number like this: “element_2″.

The working code will then be:

<ul id="sort2">
  <li id="element_1">
    <div>box no 1</div>
  </li>
  <li id="element_2">
    <div>box no 2</div>
  </li>
  <li id="element_3">
    <div>box no 3</div>
  </li>
</ul>
  • box no 1
  • box no 2
  • box no 3

Serialized output (updated when a box is dragged):Output will be shown here

I hope this tip is helpfull.

3 Responses to “Getting position from jQuery UI sortable”

  1. Getting position from jQuery UI sortable | Webdevelopment at huuah.com | Search engine optimization - SEO - Durban - KZN Says:

    [...] Read this article: Getting position from jQuery UI sortable | Webdevelopment at huuah.com [...]

  2. J Says:

    This construct works well:

    $(“#sort3″).sortable({
    update: function(event, ui) {
    ids = [];
    $(“#sort3 li”).each(function(n){
    ids.push($(this).attr(‘id’));
    });
    alert(ids); // or show ids through the DOM.
    });

    The alert shows the reordered list of id’s. Enjoy.

  3. Martin Streicher Says:

    Why is this not documented anywhere? I like the suggestion from J.

Leave a Reply