Reputation: 4326
I have this HTML:
<ul>
<li>a</li>
<li>b</li>
</ul>
I apply this:
$('ul').sortable()
After changing the order of the elements, I can see DOM changes in Chrome's Inspect Element, but selecting the sorted elements in console or in another function $('ul li')
returns an initial order.
How to get the elements list in the new order?
Upvotes: 1
Views: 538
Reputation: 21150
It works fine, but you need to tell jQuery something happened. So e.g. you should ask for the order of the li
items after any sortable() function has been called.
As an example:
$(function() {
$( "#sortable" ).sortable({
revert: true,
start: function(evt, ui) {
$('#log').html("");
},
stop: function(evt, ui) {
//alert( $( "li" ).first().html() );
$( "li" ).each(function( index ) {
$('#log').append( $( this ).text() + " " );
});
}
});
});
Where I loop through each $("li")
and it gives the correct order.
See this jsFiddle for the result:
Instead of writing all your functions inside the stop:
method, you can also call any external function like below. Make sure you call it everytime the .sortable()
function is utilised.
$(function() {
$( "#sortable" ).sortable({
revert: true,
stop: function(evt, ui) {
myFunction();
}
});
});
function myFunction()
{
$('li').each(function()
{
$(this).off(); // delete any previously defined function
$(this).click(function() // define a new function
{
alert('My position is: '+$("li").index( $(this) ));
});
});
}
Of course, you don't need to do this if your function doesn't explicitly use the index of any element. Then you can just define the functions once.
Here is the last code in a jsFiddle demo:
Upvotes: 1
Reputation: 2869
If you use Chrome's developer tools's Elements section (which is very handy), then you can see the update element list like below where the li
elements are in descending order after sorting:
Upvotes: 0