Can you use jquery's sortable on a list that was made with a different jquery function?

StackOverflow https://stackoverflow.com/questions/22950355

  •  30-06-2023
  •  | 
  •  

Вопрос

It seems like it should work, but it isn't doing anything.

I have a function that makes a list when the page loads using names from an SQL database.

var contentString = "<div id='priorityDiv'><ul id='sortable' class='connectedSortable'>";

for (var cntr = 0; cntr < listOfPeople.length; cntr++) 
{
     contentString = contentString + "<li class='ui-state-default' id='user_" + cntr + "'>" + listOfPeople[cntr].userFullName + "</li>"
}
contentString = contentString + "</ul></div>";

Then I append contentString to a div, and that works just fine and looks good when I inspect the html once the page has loaded. There is a ul sortable list with the right list items inside.

Then, in the script part I simply have:

$(document).ready(function () {
    $("#sortable").sortable(
        {
        update: function () {
            var order = $('#sortable').sortable('toArray').toString();

            alert("Order:" + order);
        }

    }  
    ).disableSelection();
});

The stuff in the middle is to tell me the knew order of the list. So the list shows up on the page, but none of the items are moveable or sortable. Even if I just put

$(document).ready(function () {
$('#sortable').sortable();
});

It still doesn't do anything. And I do have jquery 1.9.2 in the file.

Это было полезно?

Решение

You need to bind the sortable after you create your dynamic list items. Otherwise when you bind the sortable, it doesn't know which element to bind to as the element doesn't exist.

One more improvement. You are binding the sortable to the parent <ul> element, if you want only the <li> elements to be able to sorted.

So try the following.

$('#sortable').sortable({
    items: ' > li',
});

Having said that it should work as it is right now because the default is > *. You can read more over here.

Другие советы

$(document).ready() is on page load, what you'd want to do is call a function that builds the list (in javascript) and then call the sortable function after it is built.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top