views:

124

answers:

2

I have a list powered by jQuery UI's sortable that allows a user to order line items. I want to have a number that represents the position of that object after it is dropped.

<ul>
     <li><span class="number">1</span> Apple</li>
     <li><span class="number">2</span> Microsoft</li>
     <li><span class="number">3</span> Canonical</li>
<ul>

Right now I have a number (not using an <ol> because I want to style/position the number... and that wouldn't solve the problem anyway). Obviously, if I were to move Canonical's line item to the top, the 3 would stay with it.

Is there way, using jQuery that I could recalculate the numbers every time a line item is dropped in place?

Thanks. :)

+2  A: 

You could use the index()+1 (or equivalent way of calculating an index) of the <li> in the parent. Something like

$('li > span.number').each(function() {
   var $this = $(this); 
   $this.text($this.parent('li').prevAll().length + 1);
});

Here's a Working Demo. Add /edit to the URL to see the code

Russ Cam
Thank you so much! Worked like a charm! :)
Bryan Veloso
+3  A: 

Shorter:

$('li > span.number').each(function(i) {
   var $this = $(this); 
   $this.text(i+1);
});
Joel L
+1 -- good call
Russ Cam