Mayeenul Islam
Mayeenul Islam

Reputation: 4762

jQuery UI Sortable - how to set data, based on the got data

I'm using jQuery UI Sortable to let the user sort on a queried data, and saving the sorted data into another table. I'm putting the changed order into a hidden field and saving the data.

HTML

<?php
// $queried_data is queried in LIFO order from a table, suppose an order like: 1,2,3,4
$saved_data = '2,3,4,1'; //queried as a string from another table
?>
<div class="data-sorter">
    <ul id="sortable-data">
    <?php foreach($queried_data as $key => $value) : ?>
        <li id="<?php echo $value->ID; ?>">
            <?php echo $value->title; ?>
        </li>
    <?php endforeach; ?>
    </ul>
    <!-- HIDDEN FIELD: putting saved data here, and updating according to the changed data, and finally saving as a comma-separated string -->
    <input type="hidden" class="data-sorted" value="<?php echo $saved_data; ?>">
</div>

JAVASCRIPTS

jQuery( document ).ready(function($) {
    "use strict";

    var sortable_data = $( "#sortable-data" );

    sortable_data.sortable({
        update: function( event, ui ) {
            var list_id     = this.id,
                item_moved  = ui.item.attr('id'),
                order       = $(this).sortable('toArray'),
                positions   = order.join(',');

            var hidden_field = $('#'+ list_id).parent().find('.data-sorted');

            hidden_field.val(positions).trigger('change');
        }
    });

    sortable_data.disableSelection();

});

But as you can see the $queried_data$saved_data. So, after refresh, the PHP loop is putting things into original order. I'm okay with that. I just need to manipulate the DOM using the jQuery UI sortable so that they appear according to the order, got from the $saved_data.

I need a way to trigger jQuery UI sortable (I did in line#6 in Javascripts) as well as set the value according to the $saved_data (that available as a value of the hidden field .data-sorted).

I understand that I need the Sortatble create event, but I can't figure out, how.

Upvotes: 1

Views: 417

Answers (1)

Anup Yadav
Anup Yadav

Reputation: 3005

Check this logic, should work. Considered that li id is the same as comma separated values.

On page load call function reorder() after sortable call.

$("#sortable-data").sortable({update: reorder});
function reorder()
{
    orderArray = $('.data-sorted').val();
    elementContainer = $("#sortable-data")
    $.each(orderArray, function(key, val){
        elementContainer.append($("li#"+val));
    });
}

Upvotes: 1

Related Questions