Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renumbering a List using jQuery

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. :)

like image 589
Bryan Veloso Avatar asked Dec 18 '22 04:12

Bryan Veloso


2 Answers

Shorter:

$('li > span.number').each(function(i) {
   $(this).text(i+1);
});
like image 107
Joel L Avatar answered Dec 30 '22 00:12

Joel L


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

like image 42
Russ Cam Avatar answered Dec 30 '22 01:12

Russ Cam