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. :)
Shorter:
$('li > span.number').each(function(i) {
$(this).text(i+1);
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With