Renumbering a List Using jQuery

I have a list running jQuery UI sortable that allows the user to sort positions. I want to have a number that represents the position of this object after it is deleted.

<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> 

Now I have a number (without using <ol> , because I want to style / put the number ... and this still will not solve the problem). Obviously, if I moved the Canonical position to the top, it would stay with it.

Is there a way using jQuery so that I can recalculate numbers every time a position drops in place?

Thanks.:)

+4
source share
2 answers

In short:

 $('li > span.number').each(function(i) { $(this).text(i+1); }); 
+9
source

You can use index() +1 (or the equivalent way to calculate the index) <li> in the parent. Sort of

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

Here is a working demo . Add / change url to see code

+3
source

All Articles