Rockwell Rice Rockwell Rice - 5 months ago 34
Javascript Question

How to get jquery sortable to run function on button click

I have some code that will gather up the sort of a sortable list and turn it into an array. The code is set up to work on the drop event, so when you drag an item and then drop it the array is created and sent out. I need to change this so that it is triggered by a button click instead, for some reason turning this into a click event will not work though.

Here is the function as it is now

$(document).ready(function(){

$('#sortable-stages').sortable({
update: function(event, ui) {
var stage = document.getElementsByClassName('stage');
var stageOrder = $(this).sortable('toArray');
$.get('/stages/reorder', { 'order' : stageOrder });
}
});

});


Any help on how to turn this code into something that is triggered by a button click would be great.

I did try the obvious

$(document).on('click','#stagereorderbutton', function() {
//...
});


and that did not run the code even though it would trigger an alert, but only if placed right at the beginning, above the
update:
part.

Answer

If I well understand your question, you should simply get the array of sortable items on button click:

$(document).ready(function(){

    var items = $('#sortable-stages').sortable(/*options...*/);
    $(document).on('click','#reorderbutton',function(){
        $.get('/stages/reorder', { 'order' :  items.sortable('toArray') });
    });

});

JSFiddle Demo


If you need the update option, you can define an variable outside of the scope, update it inside scope and use it on button click:

$(document).ready(function(){

    var stageOrder;
    $('#sortable-stages').sortable({
        update: function(event, ui) {
            var stage = $('.stage');
            stageOrder = $(this).sortable('toArray');
        }
    });
    $(document).on('click','#reorderbutton',function(){
        $.get('/stages/reorder', { 'order' :  stageOrder });
    });

});