Drag and Drop Table Rows in JavaScript|Reorder, Copy, and Delete Rows Easily
This page provides a JavaScript table drag and drop example that allows you to reorder HTML table rows by dragging.
Using the lightweight script mamdragdrop.js, you can also enable row copy (Ctrl + Drag) and row delete (Alt + Click).
// Settings this.canCtrlDropCopy = true; // Enable row copy with Ctrl + Drop this.canAltClickDelete = true; // Enable row delete with Alt + Click
■How to Use
-
Download
mamdragdrop.jsusing the button above.
-
In the file where you want to use mamdragdrop, include the script like this:
<script src="./js/mamdragdrop.js"></script>
Use either a relative or absolute path to specify the JavaScript file. -
Add
class="mam_dragdrop"to the table element where you want to enable drag & drop.
To correctly detect non-draggable header rows, make sure to include both<thead>and<tbody>tags.<table class="mam_dragdrop"> <thead> <tr> <th>Column Title1</th> <th>Column Title2</th> </tr> </thead> <tbody> <tr> <td>Cell1-1</td> <td>Cell1-2<input type="text" style="width:128px;" maxlength="8" value="draggable table" name="tx[]"></td> </tr> <tr> <td>Cell2-1</td> <td>Cell2-2<input type="text" style="width:128px;" maxlength="8" value="text" name="tx[]"></td> </tr> <tr> <td>Cell3-1</td> <td>Cell3-2<input type="text" style="width:128px;" maxlength="8" value="text3-2" name="tx[]"></td> </tr> <tr> <td>Cell4-1</td> <td>Cell4-2<input type="text" style="width:128px;" maxlength="8" value="text4" name="tx[]"></td> </tr> </tbody> </table>
■Usage Example
You can drag and drop the
icon on each row to move rows within the table.
Holding the CTRL key while dragging will copy the row instead of moving it.
Holding the ALT key and clicking the
icon will delete the row.
(You cannot delete all rows. The last remaining row cannot be removed.)
| Column Title1 | Column Title2 |
|---|---|
| Cell1-1 | Cell1-2 |
| Cell2-1 | Cell2-2 |
| Cell3-1 | Cell3-2 |
| Cell4-1 | Cell4-2 |
