Html table drag and drop rows

How to create Dynamic Drag and Drop table rows using jQuery Ajax ?

In this article, we will discuss the method of How to create Dynamic and Drop table rows using JQuery Ajax. We will use jQuery and HTML CSS to perform the operations of Drag and Drop on the table row.

First to perform the operations of the Drag and Drop table row we need two jQuery libraries without these libraries we can’t perform the Drag and Drop operations on the table row. The required two libraries are:

  • jQuery Ajax min.js: It will help us to perform the Drag and Drop operation on the table row:
  • jQuery-UI: This as the name suggests, it’s used for showing user interface operations:

Basically Drag and Drop operations on table rows means we can interchange the table row with each other by only operating Drag and Drop operations we need to only Drag and one row Drop it on another row with which we want to perform Drag and Drop operations it’s basically used for change data and for the correctness of data when we write or add wrong data on a table.

Approach: First we create table by using table and td , tr tag in our html code and we add one h1 tag for heading through which i explained what we are making and in first tag or tr we add three column first for id second, language and last one for preference and we add id 1 to 8 and in language we write some coding language and at last we are adding preference which we will set stable it means when we will perform Drag and Drop operations so that preference will not change their sequences its always static 1 to 8 only two column / row change id and preference according to perform operation by user and after writing code for table we add jQuery libraries without which we can’t operate Drag and Drop operations and the we give id in table GFG and at last we write js first we create one function in which we will use GFG id and we will use sortable method and we use droponEmpty as a false default and after we start operation by using one more function and we addclass select and for stop the operation we will make one other function and set the stop function and write code for stop and successful showing interchange table operations on table row and we set GFG greater than 0 which and use findmethod in which we use td for Drag and Drop operations so with the help of these code we can perform Drag and Drop operations on table row.

Читайте также:  Static var in class php

Example: This is the implementation of the above approach:

Источник

Drag and drop table row

Before taking a look at this example, it’s recommended to visit this post to know how we can drag and drop element in a list.

Now we can use the same technique to apply to the table rows. The basic idea is

  • When user starts moving the table row, we create a list of items. Each item is cloned from each row of table.
  • We show the list at the same position as table, and hide the table.
  • At this step, moving row around is actually moving the list item.
  • When user drags an item, we determine the index of target item within the list. And move the original dragged row to before or after the row associated with the end index.

Let’s get started with the basic markup of table:

Basic setup

As mentioned in the Drag and drop element in a list example, we need handle three events:

  • mousedown for the first cell of any row, so user can click and drag the first cell in each row
  • mousemove for document : This event triggers when user moves the row around, and we will create and insert a placeholder row depending on the direction (up or down)
  • mouseup for document : This event occurs when user drags the row.

Here is the skeleton of these event handlers:

// Query the table
const table = document.getElementById('table');

const mouseDownHandler = function(e)
.

// Attach the listeners to `document`
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
>;

const mouseMoveHandler = function(e)
.
>;

const mouseUpHandler = function()
.
// Remove the handlers of `mousemove` and `mouseup`
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
>;

// Query all rows
table.querySelectorAll('tr').forEach(function(row, index)
// Ignore the header
// We don't want user to change the order of header
if (index === 0)
return;
>

// Get the first cell of row
const firstCell = row.firstElementChild;
firstCell.classList.add('draggable');

// Attach event handler
firstCell.addEventListener('mousedown', mouseDownHandler);
>);

Clone the table when user is moving a row

Since this task is performed once, we need a flag to track if it’s executed:

let isDraggingStarted = false;

const mouseMoveHandler = function(e)
if (!isDraggingStarted)
isDraggingStarted = true;

cloneTable();
>
.
>;

cloneTable creates an element that has the same position as the table, and is shown right before the table:

let list;

const cloneTable = function ()
// Get the bounding rectangle of table
const rect = table.getBoundingClientRect();

// Get the width of table
const width = parseInt(window.getComputedStyle(table).width);

// Create new element
list = document.createElement('div');

// Set the same position as table
list.style.position = 'absolute';
list.style.left = `$rect.left>px`;
list.style.top = `$rect.top>px`;

// Insert it before the table
table.parentNode.insertBefore(list, table);

// Hide the table
table.style.visibility = 'hidden';
>;

Imagine that list consists of items which are cloned from the table rows:

const cloneTable = function()  
.

// Loop over the rows
table.querySelectorAll('tr').forEach(function(row)
const item = document.createElement('div');

const newTable = document.createElement('table');
const newRow = document.createElement('tr');

// Query the cells of row
const cells = [].slice.call(row.children);
cells.forEach(function(cell)
const newCell = cell.cloneNode(true);
newRow.appendChild(newCell);
>);

newTable.appendChild(newRow);
item.appendChild(newTable);

list.appendChild(item);
>);
>;

After this step, we have the following list :

 
div>

div>
table>

tr>
.
tr>
table>
div>


div>
table>

tr>
.
tr>
table>
div>


div>


table>
.
table>

It’s worth noting that when cloning cells in each item, we have to set the cell width same as the original cell. So the item looks like the original row completely:

cells.forEach(function (cell)  
const newCell = cell.cloneNode(true);
// Set the width as the original cell
newCell.style.width = `$parseInt(window.getComputedStyle(cell).width)>px`;
newRow.appendChild(newCell);
>);

Determine the indexes of dragging and target rows

let draggingEle; // The dragging element
let draggingRowIndex; // The index of dragging row

const mouseDownHandler = function (e)
// Get the original row
const originalRow = e.target.parentNode;
draggingRowIndex = [].slice.call(table.querySelectorAll('tr')).indexOf(originalRow);
>;

const mouseMoveHandler = function (e)
if (!isDraggingStarted)
cloneTable();

// Query the dragging element
draggingEle = [].slice.call(list.children)[draggingRowIndex];
>
>;

const mouseUpHandler = function ()
// Get the end index
const endRowIndex = [].slice.call(list.children).indexOf(draggingEle);
>;

As we have draggingRowIndex and endRowIndex , it’s now easy to check if user drops to the top or bottom of table. And we can decide how to move the target row before or after the dragging row:

const mouseUpHandler = function ()  
// Move the dragged row to `endRowIndex`
let rows = [].slice.call(table.querySelectorAll('tr'));
draggingRowIndex > endRowIndex
? // User drops to the top
rows[endRowIndex].parentNode.insertBefore(rows[draggingRowIndex], rows[endRowIndex])
: // User drops to the bottom
rows[endRowIndex].parentNode.insertBefore(rows[draggingRowIndex], rows[endRowIndex].nextSibling);
>;

Following is the final demo. Try to drag and drop the first cell of any row.

Demo

See also

  • Add or remove class from an element
  • Attach or detach an event handler
  • Calculate the mouse position relative to an element
  • Clone an element
  • Create an element
  • Drag and drop element in a list
  • Drag and drop table column
  • Drag to scroll
  • Get siblings of an element
  • Insert an element after or before other element
  • Loop over a nodelist
  • Make a draggable element
  • Remove an element
  • Select an element or list of elements
  • Set css style for an element

Источник

Reorder HTML table rows using drag-and-drop

I have a jQuery function to move table rows up and down. I do not know how to save the data, nor get the position of each row. I am using PHP to show the table rows. How do I get each table row position value when the user reorders the table rows?

6 Answers 6

The jQuery UI sortable plugin provides drag-and-drop reordering. A save button can extract the IDs of each item to create a comma-delimited string of those IDs, added to a hidden textbox. The textbox is returned to the server using an async postback.

This fiddle example reorders table elements, but does not save them to a database.

The sortable plugin takes one line of code to turn any list into a sortable list. If you care to use them, it also provides CSS and images to provide a visual impact to sortable list (see the example that I linked to). Developers, however, must provide code to retrieve items in their new order. I embed unique IDs of each item in the list as an HTML attribute and then retrieve those IDs via jQuery.

// ----- code executed when the document loads $(function() < wireReorderList(); >); function wireReorderList() < $("#reorderExampleItems").sortable(); $("#reorderExampleItems").disableSelection(); >function saveOrderClick() < // ----- Retrieve the li items inside our sortable list var items = $("#reorderExampleItems li"); var linkIDs = [items.size()]; var index = 0; // ----- Iterate through each li, extracting the ID embedded as an attribute items.each( function(intIndex) < linkIDs[index] = $(this).attr("ExampleItemID"); index++; >); $get("").value = linkIDs.join(","); > 

Источник

Drag and drop table rows with JavaScript

REDIPS.drag was initially built to drag and drop table content. After publishing first version of REDIPS.drag, I received a lot of questions about dragging table rows also. Now is possible to drag and drop table rows as well as table content. First column and contained DIV element in this demo is a row handler, so you can try to drag table rows.

It is very easy to define a row handler. Actually, it is only needed to place DIV element to the column (first, last or any other) and to define row”. This DIV element will become a row handler. When row dragging begins, source row will change color and content will become transparent. This way, source row as start point is visible and obvious. It is possible to return row to the start point – in this case, event.rowDroppedSource() will be fired. In a moment when row is dropped to the destination table, source row will be removed. How REDIPS.drag works? The trick is to clone a mini table from the source table and to remove all rows except selected row. It looks like a row, but it is a table with only one row – a mini table. New functionality also brings new event handlers:

  1. event.rowChanged
  2. event.rowClicked
  3. event.rowCloned
  4. event.rowDeleted
  5. event.rowDropped
  6. event.rowDroppedBefore
  7. event.rowDroppedSource
  8. event.rowMoved
  9. event.rowNotCloned
  10. event.rowNotMoved
  11. event.rowUndeleted

Each event handler has access to the obj and objOld objects. For example, event.RowClicked() sees only obj object and this is reference to the source row. event.rowMoved() is fired in a moment when dragging starts and in this case, obj is reference to the mini table (previously mentioned) while objOld is reference to the source table row.

REDIPS.drag has a new method: rowOpacity(el, opacity, color) to change color and opacity of the source row and mini table. This way it is only needed to call rowOpacity() method in event handlers to have row effects like in this demo. Here is code for event.rowMoved() used in this demo:

rd.event.rowMoved = function () < // set opacity for moved row // rd.obj is reference of cloned row (mini table) rd.rowOpacity(rd.obj, 85); // set opacity for source row and change source row background color // rd.objOld is reference of source row rd.rowOpacity(rd.objOld, 20, 'White'); // display message msg.innerHTML = 'Moved'; >;

REDIPS.drag takes care about background color of table cells and table rows. When dragging begins, color of each table cell is saved to the array and returned in a moment of dropping or highlighting current table row. Source code of REDIPS.drag library with examples can be download from “download icon” below post title. If you want to see more drag and drop examples based on REDIPS.drag, click on Drag and Drop category.

Happy dragging and dropping!

Источник

Оцените статью