Search code examples
javascriptjqueryjquery-uijquery-ui-sortablesortables

jQuery-ui sortable - Again enable sortable after it has been disabled


I have the following jQuery code:

var isOk = true;
$('#edit').click(function () {
    if (isOk) {
        $('table tbody').sortable({
            axis: 'y',
            update: function (event, ui) {
                var data = $(this).sortable('serialize');
                $.ajax({
                    data: data,
                    type: 'POST',
                    url: 'updatePagesOrder.php',
                    success: function (msg) { //re-number the rows from 1 to n
                        $('table > tbody tr').each(function (i) {
                            $(this).attr('id', 'item-' + (i + 1)); // use $(this) as a reference to current tr object
                        });
                    },
                    error: function () {
                        alert("An error occurred");
                    }
                });
            }
        }, "enable");
    }
    else {
        $("table tbody").unbind();
        $('table a').unbind();
    }
    isOk = !isOk;

In the code above #edit is a button, on the first click it cause the table rows to be sorable, and on the second click it disable the sortable option.

I want that on the third click the rows will be sortable again. I tried the code above, but it didn't work.

Why? and how can I fix it? Thanks!


Solution

  • Initialize the widget outside the click handler:

    $('table tbody').sortable({
        disabled: true, // Initially disabled
        axis: 'y',
        update: function (event, ui) {
            var data = $(this).sortable('serialize');
            $.ajax({
                data: data,
                type: 'POST',
                url: 'updatePagesOrder.php',
                success: function (msg) { //re-number the rows from 1 to n
                    $('table > tbody tr').each(function (i) {
                        $(this).attr('id', 'item-' + (i + 1)); // use $(this) as a reference to current tr object
                    });
                },
                error: function () {
                    alert("An error occurred");
                }
            });
        }
    });
    

    Then just toggle the "disabled" option when you click on the button.

    $("#edit").click(function() {
        var table = $('table tbody');
        table.sortable('option', 'disabled', !table.sortable('option', 'disabled'));
    });