开发者

How to dynamically sort elements and save multiple changes on submit

I have this view with a receipe that has many ingredients. I want to be able to dynamically sort my ingredients and only send the changes to the controller once, when hitting the submit button for the whole form. I've been googling this for quite a while and I do see many question regarding this, though not any answers... I'm quite familiar with rails, but just starting out with javascript.

View

<% form_for @receipe do |r| %>  
  <%= r.text_field.name %>  
  <% f.fields_for :receipe_ingredients do |ri| %>  
    <%= ri.fields_for :ingredients do |i| %>  
      <%= link_to i.object.name, ingredient_path(i.object.id) %>  
      <%= ri.text_field :specification %>  
    <% end %>  
  <% end %>  
<%= r.submit "save" %&g开发者_如何学运维t;  
<% end %>  
<%= link_to "add more ingredients", ingredients %> 


You don't mention if you are using jquery or prototype. I assume Prototype, check this:

http://madrobby.github.com/scriptaculous/sortable-lists-demo/


Place the ingredients in a list, than use javascript to make them sortable. This seems llike a good plugin for that.

Than on submit, block the usual reloading of the page with something like

$("#submit").preventDefault();

and send the data in the javascript array to your rails app with ajax. Compare the old order on the server with the new order in the javascript array, and make the adjustments to their order. I think that should help.

I you don't want to use ajax, load the javascript array in a hidden textfield in json format every time the user changes the order, and make your controller work with that json string to find out the order of the items.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜