2008年9月22日星期一

JQuery: Drag Drop Sort

updated: add the html,

this is the html,


    <% @pages.each do |p| %>
  • ">
    <%= p.title %>
    <% if p.has_children? %>
      ">
      <% p.children.each do |c| %>
    • " class="sortable_submenu"><%= c.title %>

    • <% end -%>

    <% end -%>

  • <% end -%>


if you know the rails, it is easy :) .

--------------------------------------------------------------------------------------------------------------------------------

I need a "Drag Drop Sort " tree in my project. I found some jquery plugins, but all of them seems can't solve my problem, so I decided to solve it use JQuery UI.
All I need are 'jquery-ui-core', 'jquery-draggable', 'jquery-droppable','jquery-sortable',
these you can download from JQuery site.
Then some code like this:


$(".assets li").draggable({
helper: 'clone'
});
$(".drop").droppable({
accept: ".drag",
activeClass: 'droppable-active',
hoverClass: 'droppable-hover',
drop: function(ev, ui){
var drag = ui.draggable;
drag.appendTo($(this).siblings('ul.assets'))
$.ajax({
dataType: "script",
type: "PUT",
url: url,
data: "asset[category_id]=" + $(this).attr('id')
});
}
});
$("#sort").sortable({
items: '.sortable',
stop: function(e, ui){
var data = $(this).sortable("serialize")
$.ajax({
url: "/back/pages/sort",
type: "POST",
data: data,
dataType: "script"
});
}
});



The code is simple, there are some useful callbacks you can use, like start, stop, drop..., you can find them in the doc.

In the sort, this function "$(this).sortable("serialize") " will return the sort result.It works by default by looking at the id of each item in the format 'setname_number', and it spits out a hash like "setname[]=number&setname[]=number".

So do you think JQuery is amazing? Let's Rock!

1 条评论:

Glen 说...

This looks like it might help me with a project I am working on, too. Can you post the sample HTML that goes with the jQuery code? I cannot quite figure out what elements to apply the classes to.