user3591872
user3591872

Reputation: 47

How to do draggable and sortable in table body td using jquery ui

Draggable is working right now and I want the sortable procedure to work also with these columns. These are simple div elements that I want to sortable using jQuery UI. Kindly let me know if there is anything wrong with the code below.

<table class="table table-bordered table-condensed">
    <thead>
        <tr>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>File A</td>
            <td><span id="draggable" class="label label-default ui-widget-content filediv"> </span></td>
            <td></td>
            <td><span id="draggable1" class="label label-default ui-widget-content filediv"> </span></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
        <tr>
            <td>File B</td>
            <td></td>
            <td><span id="draggable2" class="label label-success ui-widget-content filediv"> </span></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </tbody>
</table>
<script>
   $( function() {
   $( "#draggable" ).draggable();
   $( "#draggable1" ).draggable();
   $( "#draggable2" ).draggable();
  } );
</script>

Upvotes: 0

Views: 5279

Answers (1)

Twisty
Twisty

Reputation: 30903

I took some guesses, but I think you want to Drag and Drop, not Sort.

Example: https://jsfiddle.net/g21dso7e/2/

CSS

.table-bordered {
  border: 1px solid #000;
}

.table-condensed {
  border-collapse: collapse;
}

.table tr {
  padding: 0.2em;
  border: 1px solid #000;
}

.table tr td {
  border-left: 1px solid #000;
  min-width: 1.5em;
  min-height: 1.5em;
  position: relative;
}

.table tr td span.label {
  position: absolute;
  top: 0.4em;
  left: 0.2em;
}

JavaScript

$(function() {
  $(".label").draggable();
  $(".table tbody tr td").droppable({
    accept: ".label",
    drop: function(e, ui) {
      ui.draggable.appendTo($(this)).css({
        top: "0.4em",
        left: "0.2em"
      });
    }
  });
});

Since you have a class of label for each, I would use this as a single selector. When draggable is used in conjunction with droppable, you can then append the dropped item to an element. Draggable simply adjusts it's position but does not change it's place in the DOM.

When the item is dropped on a table cell, the drop callback does the work for us. The CSS helps drop the item into the right position in the cell.

Upvotes: 2

Related Questions