Michael Choi
Michael Choi

Reputation: 134

jQuery UI Sortable linked elements

I have two columns, each with many rows/divs. I'm trying to get jQuery UI Sortable to work in a way that if I drag a div in the left column, the associated row/div in the right column will be sorted as well.

For example,

<html><body>
  <div class='left-column'>
    <div class='field' id='left_1'>content 1</div>
    <div class='field' id='left_2'>content 2</div>
    <div class='field' id='left_3'>content 3</div>
  </div>
  <div class='right-column'>
    <div class='field' id='right_1'>content 1</div>
    <div class='field' id='right_2'>content 2</div>
    <div class='field' id='right_3'>content 3</div>
  </div>
</body></html>

As for the jQuery, right now I have,

function linkedSort() {
  $('.left-column').sortable({ 
    axis: 'y',
    stop: function(event, ui) {
      $('.left-column .field').each(function(i, field) {
        var fieldName = $(field).attr('id');
        var fieldNumber = fieldName.substr(fieldName.indexOf('_')+1);
        // do something here to place it in the right area
      });
    }
  });
};

If I drag .left-column .field_2 below .field_3, the respective divs in .right-column should rearrange themselves as well.

Thanks!

Upvotes: 1

Views: 717

Answers (1)

hitmanDX
hitmanDX

Reputation: 245

I think this might be what you are looking for:

<div class='left-column'>
    <div name='field_1'>content 1</div>
    <div name='field_2'>content 2</div>
    <div name='field_3'>content 3</div>
  </div>
  <div class='right-column'>
    <div name='field_1'>content 1</div>
    <div name='field_2'>content 2</div>
    <div name='field_3'>content 3</div>
</div>

$('.left-column').sortable({
    axis: 'y',
    stop: function(event, ui) {
        $('.left-column div[name^=field_]').each(function(i, v) {
            $('.right-column').find("[name=" + $(v).attr('name') + "]").appendTo($('.right-column'));
        });
    }
});
$('.right-column').disableSelection();

Upvotes: 2

Related Questions