Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder HTML table rows using drag-and-drop

Tags:

jquery

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?

like image 416
Farshad Avatar asked Jan 15 '10 15:01

Farshad


People also ask

How do I move a row in a table in HTML?

</table> $('#mytable input. move'). click(function() { var row = $(this). closest('tr'); if ($(this).

How do you drag and drop rows?

Drag the rows or columns to another location. Hold down OPTION and drag the rows or columns to another location. Hold down SHIFT and drag your row or column between existing rows or columns. Excel makes space for the new row or column.

How do I use draggable JS?

By default, only image and text can be draggable. To drag an image, you simply hold the mouse button down and then move it. To drag the text, you need to highlight some text and drag it in the same way as you would drag an image.


1 Answers

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.

For example:

// ----- 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("<%=txtExampleItemsOrder.ClientID %>").value = linkIDs.join(","); } 
like image 163
Jim Petkus Avatar answered Sep 20 '22 14:09

Jim Petkus