DataTable move a row up or down
by snavarro81
HTML
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.css">
<script src="https://cdn.datatables.net/v/dt/dt-1.10.13/datatables.min.js"></script>
<table id="ArgumentsTable" class="table table-striped table-bordered dataTable"></table>
CSS
a.dtMoveUp, a.dtMoveDown {
margin-right:5px;
text-decoration: underline;
cursor:pointer;
}
JavaScript
(function ($) {
var dataArguments = [
{
"id": 1,
"name": "Param1",
"description": "Desc1",
"order": 1
},
{
"name": "Param2",
"id": 2,
"description": "Desc2",
"order": 2
},
{
"id": 3,
"name": "Param3",
"description": "Desc3",
"order": 3
}
];
var table = $('#ArgumentsTable').DataTable({
paging: false,
data: dataArguments,
columns: [
{
name: 'order',
title: 'Order',
data: 'order',
sortable: false
},
{
name: 'id',
data: 'id',
visible: false
},
{
name: 'order',
data: 'order',
visible: false
},
{
name: 'name',
data: 'name',
title: 'Name',
searchable: true,
sortable: false
},
{
name: 'description',
data: 'description',
title: 'Description',
searchable: true,
sortable: false
},
{
name: 'action',
data: null,
title: 'Action',
searchable: false,
sortable: false,
render: function (data, type, full, meta) {
if (type === 'display') {
var $span = $('<span></span>');
if (meta.row > 0) {
$('<a class="dtMoveUp">Up</a>').appendTo($span);
}
$('<a class="dtMoveDown">Down</a>').appendTo($span);
return $span.html();
}
return data;
}
}
],
'drawCallback': function (settings) {
$('#ArgumentsTable tr:last .dtMoveDown').remove();
// Remove previous binding before adding it
$('.dtMoveUp').unbind('click');
$('.dtMoveDown').unbind('click');
// Bind clicks to functions
$('.dtMoveUp').click(moveUp);
$('.dtMoveDown').click(moveDown);
}
});
// Move the row up
function moveUp() {
var tr = $(this).parents('tr');
moveRow(tr, 'up');
}
// Move the row down
function moveDown() {
var tr = $(this).parents('tr');
moveRow(tr, 'down');
}
// Move up or down (depending...)
function moveRow(row, direction) {
var index = table.row(row).index();
var order = -1;
if (direction === 'down')...