How can I specify reordering of list items using jquery?

I am using jquery sortable.

right now I have a list of items that I can ALREADY use drag and drop. which is cool.

I will use the submit button at the bottom of the list to submit a new order. the change in the list will not be automatically submitted.

All I need is some indication that the position of the element has changed. I've searched a lot. no answer.

original list:

item1 item2 item3 item4 Item5

submitbutton here.

list changed: I moved item 2 under item 3, for example,

item1 item3 item2 * item4 Item5

submitbutton here.

how can i use sorting in jquery to display sign on item 2?

I think there should be a sort change event, but I still don't know how to use it since I'm new to jquery.

http://docs.jquery.com/UI/Sortable#event-change

thank.

+2


source to share


2 answers


I think you need to have an ordered list of items (1. Item 1, 2. Item 2, 3. Item 3), and then when one item is moved, you want to renumber the list, right? So if 2 moves below three, you need the text to say something like 1. Point 1, 2. Point 3, 3. Point 2. If I'm right, your code will look something like this. First, this is how your HTML looks like.

<ul id="yourSortableListID">
   <li class="renumberMe"><span class="list_num"></span> Item 1</li>
   <li class="renumberMe"><span class="list_num"></span> Item 2</li>
   <li class="renumberMe"><span class="list_num"></span> Item 3</li>
</ul>

      

Your JavaScript will look something like this:



function renumberListItems() {
    i = 1;
    $(".renumberMe").each( function() {
        $(".list_num", this).text(i + ".");
        i++;
    });
}

// we don't want to add the sortable until the dom is ready
$(document).ready(function() {
    renumberListItems();
    $("#yourSortableListID").sortable({
        stop: function(event, ui) {renumberListItems();}
    });
});

      

renumberListItems () loops through each li item, then finds list_num items in it, and simply updates the text using the value i

to renumber the list. We do this by using an event stop

containing a sort (more information can be found on the Events tab on this page ) that calls any function you give it when the user moves the element and releases the mouse.

+1


source


You can provide a callback for update

for sortable

, and within that callback, open ui.item

to navigate to the element being dragged. For example:



$(function() {
  $("#sortableList").sortable({
    update: function(event, ui) {
      // Update ui.item to your requirement
    }
  });
});

      

+1


source







All Articles