Home > database >  Jquery UI sortable not working for appended rows
Jquery UI sortable not working for appended rows

Time:08-08

I am trying to use jQuery UI to make a sortable table. It is working fine for the rows already added before the page load. However, I also have function to let users to add new rows, if they need.

jQuery UI sortable function not working for these appended rows.

HTML:

<button id="add" onclick="cloneRow()">Add row(s)</button>

<table id="testTable" >
    <thead>
        <tr>
            <th></th>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
    </thead>
    <tbody>
        <tr id="rowFirst">
            <td>#</td>
            <td><input  type="text" name="c1[]"></td>
            <td><input  type="text" name="c2[]"></td>
        </tr>
        <tr>
            <td>#</td>
            <td><input  type="text" name="c1[]"></td>
            <td><input  type="text" name="c2[]"></td>
        </tr>

    </tbody>
</table>

JS:

            function cloneRow() {
                var rowAmount = document.getElementById("rowAmount").value;
                var getTotalRows = $('table > tbody').children().length;
                for (var i = -1; i < rowAmount - 1; i  ) {
                    var row = document.getElementById("rowFirst"); // find row to copy
                    var table = document.getElementById("testTable"); // find table to append to
                    var clone = row.cloneNode(true); // copy children too
                    clone.id = "newRow"   (getTotalRows   i); // change id or other attributes/contents
                    clone.classList.remove('hidden');
                    table.appendChild(clone); // add new row to end of table
                    $('#newRow'   (getTotalRows   i)).children().each(function() {
                        $(this).children().attr('id', $(this).children().attr('id')   (getTotalRows   i));
                    });

                }
            }


$("table tbody").sortable({});

https://jsfiddle.net/brkztrk/3odnr4t2/5/

As you can see first two rows are perfectly sortable, but rows appended by cloneRow() function are not sortable.

does anybody has any idea how to fix this?

Thanks a lot!

CodePudding user response:

Consider the following: https://jsfiddle.net/Twisty/srm7fyo3/

JavaScript

function cloneRow() {
  var rowAmount = $("#rowAmount").val();
  for (var i = 0; i <= rowAmount; i  ) {
    var clone = $("#rowFirst").clone();
    clone.attr("id", "new-row-"   $('table > tbody > tr').length);
    clone.appendTo("table tbody");
    $("table tbody").sortable("refresh");
  }
}


$("table tbody").sortable({
  items: "> tr",
  handle: "td:eq(0)"
});

As new rows are created, the Sortable is refreshed. This way they each become a sortable item.

  • Related