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

3.3k Views Asked by At

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.

3

There are 3 best solutions below

0
On BEST ANSWER

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');
      }
    });
0
On

I'm not entirely sure that I understood the question, but you keep piling click handlers to same elements. Either filter out those that have it, or each time you add, first remove, like so:

```

$('#drag').off("click", doit).on('click', doit);

function() doit{
//statement to check if sortable() is enabled and change state accordingly
// $(this) will be jquery reference to "#drag" element
}

```

0
On

Thanks guys for your help! I am sorry I could not explain the problem precisely. However I used your input and ended up with the following code:

$('#drag').on('click', function () {
    event.preventDefault();
    $(this).toggleClass('sortable');
    if ($('#drag').hasClass('sortable')) {
        $('#div ul').sortable();
    } else {
        $('#div ul').sortable('destroy');
    }
});

The above code will enable and disable sortable() but it will not apply sortable() to newly appended elements. For those I used the following lines within the function that appends those lists.

if ($('#drag').hasClass('sortable')) {
    $('#ulid').sortable();
}