Sort & Save ordering of JqueryUI Tab: An hack


Back Again…

Few days back i was searching for JqueryUI tab sorting and get the sort order. And as we all know, this can only be possible by using sortable plugin that JqueryUI provides.
i.e. $(this).sortable(‘serialize’);

But, this code will fail in case of tab and you will not get the sort order, instead you will get `undefined`. Yeah, its a bug in ui.sortable.js.

So i came up with the hack to get the sort order of tab, the easy way.
Here we go, below is the tab html we are going to create.

<div id="tabs">
<ul>
<li id="li-1"><a id="a-1" href="#tabs-1">Nunc tincidunt (a-1)</a></li>
<li id="li-2"><a id="a-2" href="#tabs-2">Proin dolor (a-2)</a></li>
<li id="li-3"><a id="a-3" href="#tabs-3">Aenean lacinia (a-3)</a></li>
</ul>
<div id="tabs-1">
<p>Lorem Ipsum</p>
</div>
<div id="tabs-2">
<p>Dolor Sit</p>
</div>
<div id="tabs-3">
<p>Amet</p>
</div>
</div>

In order to convert above div structure into tabbed interface. we need to add
jquery.js, ui.code.js, ui.tabs.js, ui.sortable.js and finally theme css, ui.all.css, ui.tabs.css etc.

Now create tabbed interface using following code and make tabs sortable,

$("#tabs").tabs().find("ul").sortable({
        axis : "x",
        update: function (e, ui) {
              var csv = "";
             $("#tabs > ul > li > a").each(function(i){
                  csv+= ( csv == "" ? "" : "," )+this.id;
             });
             alert(csv);
        }
});

Above i have added update callback function which is been called whenever we will drag and drop tab from one position to another. And we get the id of tabs in proper order in CSV  format.

That’s it. Now go and explode that CSV value using comma in any scripting language like php, and save the array index in database to intact the sort order.

see the DEMO

Happy Coding…  🙂

Advertisement