Search code examples
javascriptjqueryjquery-uijquery-ui-sortablesortables

jQuery ui sortable: Toggle enable - disable sortable on the lists


I have multiple lists generated via AJAX in my CMS admin page which enable a user to browse various levels of content. Each list element is generated on user click on previous list. I use jQuery:

$('#divid').on('click', 'ul', function() {
  //code to modify lists
  toggle_sortable();
});

enter image description here

Now I am trying to add a toggle button "Drag" to enable and disable jQuery-UI sortable(). However, since the lists are generated dynamically, I am unable to implement this flawlessly. Currently toggle_sortable() looks like:

function toggle_sortable() {
  $('#drag').on('click', function(){
    //statement to check if sortable() is enabled and change state accordingly
  });
}

Please help me find a solution in this situation. Basically I am unable to determine whether sortable() is enabled on a particular list.


Solution

  • Here is the working DEMO to initialize the list dynamically and Toggle sortable on the list on click of a button.

    To enable/disable sortable you can use the function as show below:

    $('#toggle').click(function() {
            //check if sortable() is enabled and change and change state accordingly
          // Getter
          var disabled = $("#sortable").sortable( "option", "disabled" );
          if (disabled) {
            $("#sortable").sortable( "enable" );
            $('#status').html('Sortable is now Enabled!!');
          }
          else {
            $("#sortable").sortable("disable");
            $('#status').html('Sortable is Disabled');
          }
        });