Search code examples
jqueryjquery-uijquery-ui-sortablenested-sortable

How to add and return an extra (second) attribute to sortable/nestedSortable response?


I have a list which uses sortable/nestedSortable. What I want is to return a second attribute. I mean besides the default returning id (menuItem_n) I want to return a second attribute, for example data-type. I know that I can customize the attribute and change the default attribute (which is id) but how can I add an extra attribute.

For example:

  <ol class="sortable">
    <li id="menuItem_1" data-type="type_1">Item A1</li>
    <li id="menuItem_2" data-type="type_1">Item A2</li>
    <li id="menuItem_3" data-type="type_1">Item A3</li>
    <li id="menuItem_4" data-type="type_2">Item B1</li>
    <li id="menuItem_5" data-type="type_2">Item B2</li>
    <li id="menuItem_6" data-type="type_2">Item B3</li>
  </ol>

and then pass it with something like:

$('ol.sortable').nestedSortable('serialize', {attribute: 'id, data-type'});

Solution

  • Okay I have missed something about the nestedSortable plugin. Actually I missed it because it was an update which was not added to the documentation of the plugin (yet). According to this update, you can now add data-* attributes to the li element which you can return later with the toHierarcy output. As for the example:

      <ol class="sortable">
        <li id="menuItem_1" data-type="type_1">Item A1</li>
        <li id="menuItem_2" data-type="type_1">Item A2</li>
        <li id="menuItem_3" data-type="type_1">Item A3</li>
        <li id="menuItem_4" data-type="type_2">Item B1</li>
        <li id="menuItem_5" data-type="type_2">Item B2</li>
        <li id="menuItem_6" data-type="type_2">Item B3</li>
      </ol>
    

    so when you use:

    $('ol.sortable').nestedSortable('toHierarchy');
    

    you will return a string like:

          array (
            'id' => '1',
            'type' => 'type_1',
          ),
          1 => 
          array (
            'id' => '2',
            'type' => 'type_1',
          ),
          2 => 
          array (
            'id' => '3',
            'type' => 'type_1',
          ),
          3 => 
          array (
            'id' => '3',
            'type' => 'type_2',
          ),
          4 => 
          array (
            'id' => '4',
            'type' => 'type_2',
          ),
          5 => 
          array (
            'id' => '5',
            'type' => 'type_2',
          )
    

    Of course you have to convert the string into an array afterwards which isn't a big deal. Just throw the result into a variable and thats it you have got your array. Note that the id still is split so that you get only the number part but you will get the data-* attribute as a whole.