Reputation: 63
I'm using jQuery UI sortable in order to make a menu sortable.
I'm trying to set the id of list items to their current position or index so I can later update their position values in my database. However when I use firebug to inspect the html output, the id is not changed to the index value.
So if for example if I drag li.news in front of li.home, it's id should change to 0 and home's id to 1.
HTML:
<ul id="menu" class="sortable editable">
<li class="home" id="0">
<a href="index.php?page=home">home »</a>
</li>
<li class="news" id="1">
<a href="index.php?page=news">news »</a>
</li>
<li class="about us" id="2">
<a href="index.php?page=about-us">about us »</a>
</li>
</ul>
jQuery
$('.sortable > li').each(function() {
var index = $(this).index();
$(this).attr('id', index);
});
Any ideas on how I would be able to set the id to it's current position?
Upvotes: 2
Views: 1617
Reputation: 23943
First, unless you're assuming an HTML5 baseline, IDs starting with a number are not yet valid. Behavior will be unpredictable. If you absolutely had to work with this approach, I'd allow the IDs to correspond to some appropriate unique natural key, then use jQuery's data()
functions to attach information to each row.
$('.sortable > li').each( function( i,v ) {
$(this).data('sort-position',i);
});
To retrieve:
$('li#something').data('sort-position');
But more importantly, there's no reason I can see to move state information into the DOM; it makes a bad database, and exposes the risk of that state representation getting out of sync with the physical ordering. Why not just allow the re-ordering process, and when you want to update your back-end database, use the index of each element directly?
Upvotes: 1
Reputation: 25766
Try this
$('.sortable > li').each(function( index, value ) {
$(this).attr('id', 'item_'+index);
});
Upvotes: 2