tags:

views:

316

answers:

3

I have an unordered list like so:

<ul class="foo">
  <li id="asdf">
    <span class="indexnumber"></span>
    <span class="description">whatever</span>
  </li>

  <li id="asdfasdf">
    <span class="indexnumber"></span>
    <span class="description">whatever</span>
  </li>
</ul>

I want to display the index number of the list item in the indexnumber span (i.e., the first item will display 1, the second will display 2, and so on). My users will have the ability to sort the list items (using jquery ui sortable). I would like to be able to show my users a number in the list item that indicates where the list item is (and the value can change as the user re-orders the list).

How can I simply display the index position in the array using jquery? Alternately, is there an easy way to do this with the sortable events (i.e., once the list is sorted, increment or decrement the indexnumbers in all other list items as appropriate)?

+1  A: 

I guess you could add the DOM elements to an array using something like

var arr = jQuery.makeArray(document.getElementsByTagName("span"));

Then get their index using jQuery.inArray( value, array ) which returns an int.

Not very pretty though

Fiona Holder
A: 

I ended up doing the following:

$(function() {
    $(".foo").sortable({
        stop: function(event, ui) {
            var itemID = $(ui.item).attr("id");
            var items = $("li#" + itemID).parent(".foo").children();

            var updateditems = new Array();

            for (var i = 0; i <= items.length - 1; i++) {
                var singleitemID = $(items[i]).attr("id");
                var loc = i + 1;

                $("#" + singleitemID).text(loc);


                updateditems.push([singleitemID, loc]);
            }
        }
    });
});
dp
A: 
index_list = function() {
    $(".foo li").each(function(i){
        $(this).find(".indexNumber").html((i+1));
    });
}

you can call this function on document ready and on the change attribute of the sortable object

Hayden Chambers