Stop the sorting and reposition the tr using Javascript

Viewed 44

I want to Stop the sorting and reposition the tr using Javascript after clicking the cancel button in the modal. But when I run the following code I am getting an error,

Uncaught Error: cannot call methods on sortable prior to initialization; attempted to call method 'cancel'

Modal:

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria- 
 labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
           <span aria-hidden="true">&times;</span>
        </button>
      </div>
  <div class="modal-body">
    Do you really want to update the order?
  </div>
  <div class="modal-footer">
    <button id="cancel_update_order" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <button id="update_order" type="button" class="btn btn-primary">Save changes</button>
  </div>
</div>

Script:

new Tablesort(document.getElementById('table'));

var fixHelperModified = function(e, tr) {
  var $originals = tr.children();
  var $helper = tr.clone();
  $helper.children().each(function(index) {
      $(this).width($originals.eq(index).width())
  });
  return $helper;
  }


  updateIndex = function(e, ui) {
    $('#exampleModal').modal({
      backdrop: 'static',
      keyboard: false
    })

    $('#update_order').on('click', function() {
      $('td.index', ui.item.parent()).each(function (i) {
          $(this).html(i + 1);
      });
      $('#exampleModal').modal('hide');
    });

    $('#cancel_update_order').on('click', function() {
      $(this).sortable('cancel');
    });

  };

$("#table tbody").sortable({
  helper: fixHelperModified,
  stop: updateIndex
}).disableSelection();
1 Answers

When you get this error:

Uncaught Error: cannot call methods on sortable prior to initialization; attempted to call method 'cancel'

it most likely means that you're calling "cancel" on a different element than the one sorting was initialised on.

In this case, you have this code:

$('#cancel_update_order').on('click', function() { 
    $(this).sortable('cancel'); 
}); 

within that code "this" refers to cancel_update_order, the button, not the table.

If you only have one sortable (that uses the outer method updateIndex then this is quickly fixed by referring to the table that had sortable initialised:

$('#cancel_update_order').on('click', function() { 
    $("#table tbody").sortable('cancel'); 
}); 

If you want this to be more reusable, then you'll need to keep a copy of "this" when it referred to the table:

updateIndex = function(e, ui) {

    var sortableElement = this;

    $('#cancel_update_order').on('click', function() {
      $(sortableElement).sortable('cancel');
    });

  };
Related