Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag and drop sorting of table columns with jQuery

I'm using jQuery to drive my AJAX UI. I have a table of data, and I want to allow the user to reorder the columns in the table by dragging and dropping them. I'd like the user to be able to grab the header for a column and move it. The row of data underneath should follow. Note that I'm not interested in sorting the data or in reordering rows, but in allowing the user to change the order of the columns.

Is there an existing solution? I tried using the standard jQuery sortable call on the <th> elements, but of course that doesn't work. I browsed through the jQuery plugins site and didn't find anything. Will I need to write a jQuery plugin?

Edit: Note that jQuery, Dojo, etc. (the free ones) are really the only option for a JS framework. I can't get a license for anything commercial like ExtJS.

like image 403
A. Morrow Avatar asked Nov 10 '09 03:11

A. Morrow


2 Answers

There's a JQuery UI Widget called Dragtable.

Live demo

like image 200
Christoph Avatar answered Oct 16 '22 08:10

Christoph


Try this instead:

$('.sort').sortable({
  cursor: 'move',
  axis: 'y',
  update: function(e, ui) {
    $(this).sortable('refresh');
    var params = {};
    params = $('.id').serializeArray(),
      $.ajax({
        type: 'POST',
        data: {
          id : params
        },
        url: 'Your url',
        success: function(msg) {
          // Your sorted data.
        }
      });
  }
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<table class="table table-striped table-bordered">
  <thead>
    <tr>
      <th>abc</th>
      <th>xyz</th>
    </tr>
  </thead>
  <tbody class="sort">
    <tr>
      <input class="id" name="id" type="hidden" value="Your Value" />
      <td class="center"><span>Text Here</span></td>
      <td>Yes, you are done</td>
    </tr>
    <tr>
      <td>Foo</td>
      <td>Bar</td>
    </tr>
  </tbody>
</table>
like image 45
Vatsal M Avatar answered Oct 16 '22 09:10

Vatsal M