Reputation: 2866
I followed this Ryan Bates tutorial.
Awesome.
I got it to work with lists, but I've been trying to make it work with tables, more specifically the tables rendered in a partial.
<table id="habits" data-update-url="<%= sort_habits_url %>">
<% @habits.each do |habit| %>
<tbody id="habit_<%= habit.id %>">
# 2 tr's & 7 td's
</tbody>
<% end %>
</table>
With the above version the iteration multiples the tables because I am rendering this partial from the home page with <% rendered @habits %>
so I shouldn't have to include the line <% @habits.each do |habit| %>
.
So I tried this:
<table id="habits" data-update-url="<%= sort_habits_url %>">
<tbody id="habit_<%= habit.id %>">
# 2 tr's & 7 td's
</tbody>
</table>
But then only the first table can be dragged. With the first example code only the first iteration of tables can be dragged and dropped.
habit-sort.js.coffee
jQuery ->
$('#habits').sortable(
axis: 'y'
update: ->
$.post($(this).data('update-url'), $(this).sortable('serialize'))
);
Upvotes: 1
Views: 496
Reputation: 436
If are trying to handle multiple DOMs, you cannot use the DOM ID. So you'll need to replace the id by class.
Working with multiple tbodys and sorting TRs inside each tbody: http://jsfiddle.net/aron_aron/1jjhdtj2/2/
Also, if you bind <table id="habits"
, the sortable content will be the entire tbody html content.
Update
Let me try to do a simple explanation on how sortable works.
When you call $( "#item" ).sortable()
, you will be able to sort(change the position) of every children in the root of the #item.
What does it mean?
If you have the following html:
<div class="sortable_tables">
<table class="sortable_bodys">
<tbody class="sortable_trs">
<tr class="sortable_tds">
<td>ID 1</td>
<td>Item Name 1</td>
<td>Action</td>
</tr>
<tr>
So you can call the .sortable()
at any level, depending on the expected behavior.
For example, if you want to sort a entire tables, just call $( ".sortable_tables" ).sortable()
, so you will be able to change the position of any html element created inside <div class="sortable_tables">
But let's say that you want to sort the rows in the table. So, to sort TRs, you need to call the parent html .select()
. TR's parent is a tbody, so $( ".sortable_trs" ).sortable()
you will be able to sort TRs inside each tbody with the sortable_trs
class
Upvotes: 1