简体   繁体   中英

jQuery UI: How to save “sortable”?

I have a list of "tasks" and I'm using "sortable" so that a user can prioritize them, putting the most important ones on top. But of course, every time the page is refreshed they go back to their original position. I'm wondering if it's possible to save the position of the tasks?

Here's my code (it's a rails project):

<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>

  <script>
    $(document).ready(function() {
      $('.move').sortable();
      });
  </script>


<%= render "form" %>



<div class="move">
<% if !@project.tasks.blank? %>
  <% for item in @project.tasks %>
  <div class="container">
  <div class="panel panel-default">
  <div class="panel-heading">
    <div class='move'><%= item.title %></div>
  </div>
  </div>
  <div class="panel-body">
  <p>
    <div class='move'><%= item.description %></div>
  </p>
  <%= link_to "Edit", edit_project_task_path(@project, item) %> 
  </div>
  </div>
  <% end %>
<% end %>
</div>

You can use jQuery cookie and get the li position using jQuery UI sortable toArray :

Serializes the sortable's item id's into an array of string.

then in the load change the li position by swithin their position using insertAfter and eq selector.

Code:

var savedOrd = $.cookie('sortOrder');
if (savedOrd) {
    $.each(savedOrd.split(','), function (i, e) {
        $('#' + e).insertAfter('#sortable>li:eq(' + i + ')');
    });
}

$('#save').click(function () {
    var saveOrd = $('#sortable').sortable('toArray');
    $.cookie('sortOrder', saveOrd);
});

Demo: http://jsfiddle.net/IrvinDominin/amq6gt8w/

Alternatively instead of using cookie you can call two server methods to set and get the element positions.

You can find the index of the task and save it and sort based on index while displaying.

To find the index of the task on UI refer this : Fiddle

$("div").click(function(){
    var index = $("div").index($(this));
    var position =  index+1;
    $('span').html(position);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM