Reorder HTML table rows using drag-and-drop

后端 未结 7 501
無奈伤痛
無奈伤痛 2021-01-29 23:00

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

相关标签:
7条回答
  • 2021-01-29 23:36

    Easy for plugin jquery TableDnd

    $(document).ready(function() {
    
        // Initialise the first table (as before)
        $("#table-1").tableDnD();
    
        // Make a nice striped effect on the table
        $("#table-2 tr:even').addClass('alt')");
    
        // Initialise the second table specifying a dragClass and an onDrop function that will display an alert
        $("#table-2").tableDnD({
            onDragClass: "myDragClass",
            onDrop: function(table, row) {
                var rows = table.tBodies[0].rows;
                var debugStr = "Row dropped was "+row.id+". New order: ";
                for (var i=0; i<rows.length; i++) {
                    debugStr += rows[i].id+" ";
                }
                $(table).parent().find('.result').text(debugStr);
            },
            onDragStart: function(table, row) {
                $(table).parent().find('.result').text("Started dragging row "+row.id);
            }
        });
    });
    

    Plugin (TableDnD): https://github.com/isocra/TableDnD/

    Demo: http://jsfiddle.net/DenisHo/dxpLrcd9/embedded/result/

    CDN: https://cdn.jsdelivr.net/jquery.tablednd/0.8/jquery.tablednd.0.8.min.js

    0 讨论(0)
  • 2021-01-29 23:37

    Building upon the fiddle from @tim, this version tightens the scope and formatting, and converts bind() -> on(). It's designed to bind on a dedicated td as the handle instead of the entire row. In my use case, I have input fields so the "drag anywhere on the row" approach felt confusing.

    Tested working on desktop. Only partial success with mobile touch. Can't get it to run correctly on SO's runnable snippet for some reason...

    let ns = {
      drag: (e) => {
        let el = $(e.target),
          d = $('body'),
          tr = el.closest('tr'),
          sy = e.pageY,
          drag = false,
          index = tr.index();
    
        tr.addClass('grabbed');
    
        function move(e) {
          if (!drag && Math.abs(e.pageY - sy) < 10)
            return;
          drag = true;
          tr.siblings().each(function() {
            let s = $(this),
              i = s.index(),
              y = s.offset().top;
            if (e.pageY >= y && e.pageY < y + s.outerHeight()) {
              i < tr.index() ? s.insertAfter(tr) : s.insertBefore(tr);
              return false;
            }
          });
        }
    
        function up(e) {
          if (drag && index !== tr.index())
            drag = false;
    
          d.off('mousemove', move).off('mouseup', up);
          //d.off('touchmove', move).off('touchend', up); //failed attempt at touch compatibility
          tr.removeClass('grabbed');
        }
        d.on('mousemove', move).on('mouseup', up);
        //d.on('touchmove', move).on('touchend', up);
      }
    };
    
    $(document).ready(() => {
      $('body').on('mousedown touchstart', '.drag', ns.drag);
    });
    .grab {
      cursor: grab;
      user-select: none
    }
    
    tr.grabbed {
      box-shadow: 4px 1px 5px 2px rgba(0, 0, 0, 0.5);
    }
    
    tr.grabbed:active {
      user-input: none;
    }
    
    tr.grabbed:active * {
      user-input: none;
      cursor: grabbing !important;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <thead>
        <tr>
          <th></th>
          <th>Drag the rows below...</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class='grab'>&vellip;</td>
          <td><input type="text" value="Row 1" /></td>
        </tr>
        <tr>
          <td class='grab'>&vellip;</td>
          <td><input type="text" value="Row 2" /></td>
        </tr>
        <tr>
          <td class='grab'>&vellip;</td>
          <td><input type="text" value="Row 3" /></td>
        </tr>
      </tbody>
    </table>

    0 讨论(0)
  • 2021-01-29 23:38

    You may want to look at jQuery Sortable. I used it to reorder table rows.

    0 讨论(0)
  • 2021-01-29 23:44

    I working well with it

    <script>
        $(function () {
    
            $("#catalog tbody tr").draggable({
                appendTo:"body",
                helper:"clone"
            });
            $("#cart tbody").droppable({
                activeClass:"ui-state-default",
                hoverClass:"ui-state-hover",
                accept:":not(.ui-sortable-helper)",
                drop:function (event, ui) {
                    $('.placeholder').remove();
                    row = ui.draggable;
                    $(this).append(row);
                }
            });
        });
    </script>
    
    0 讨论(0)
  • 2021-01-29 23:51

    thanks to Jim Petkus that did gave me a wonderful answer . but i was trying to solve my own script not to changing it to another plugin . My main focus was not using an independent plugin and do what i wanted just by using the jquery core !

    and guess what i did find the problem .

    var title = $("em").attr("title");
    $("div").text(title);
    

    this is what i add to my script and the blew codes to my html part :

    <td> <em title=\"$weight\">$weight</em></td>
    

    and found each row $weight value

    thanks again to Jim Petkus

    0 讨论(0)
  • 2021-01-29 23:52

    Apparently the question poorly describes the OP's problem, but this question is the top search result for dragging to reorder table rows, so that is what I will answer. I wasn't interested in bringing in jQuery UI for something so simple, so here is a jQuery only solution:

    $(".grab").mousedown(function(e) {
      var tr = $(e.target).closest("TR"),
        si = tr.index(),
        sy = e.pageY,
        b = $(document.body),
        drag;
      if (si == 0) return;
      b.addClass("grabCursor").css("userSelect", "none");
      tr.addClass("grabbed");
    
      function move(e) {
        if (!drag && Math.abs(e.pageY - sy) < 10) return;
        drag = true;
        tr.siblings().each(function() {
          var s = $(this),
            i = s.index(),
            y = s.offset().top;
          if (i > 0 && e.pageY >= y && e.pageY < y + s.outerHeight()) {
            if (i < tr.index())
              tr.insertAfter(s);
            else
              tr.insertBefore(s);
            return false;
          }
        });
      }
    
      function up(e) {
        if (drag && si != tr.index()) {
          drag = false;
          alert("moved!");
        }
        $(document).unbind("mousemove", move).unbind("mouseup", up);
        b.removeClass("grabCursor").css("userSelect", "none");
        tr.removeClass("grabbed");
      }
      $(document).mousemove(move).mouseup(up);
    });
    .grab {
      cursor: grab;
    }
    
    .grabbed {
      box-shadow: 0 0 13px #000;
    }
    
    .grabCursor,
    .grabCursor * {
      cursor: grabbing !important;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <tr>
        <th></th>
        <th>Table Header</th>
      </tr>
      <tr>
        <td class="grab">&#9776;</td>
        <td>Table Cell 1</td>
      </tr>
      <tr>
        <td class="grab">&#9776;</td>
        <td>Table Cell 2</td>
      </tr>
      <tr>
        <td class="grab">&#9776;</td>
        <td>Table Cell 3</td>
      </tr>
    </table>

    Note si == 0 and i > 0 ignores the first row, which for me contains TH tags. Replace the alert with your "drag finished" logic.

    0 讨论(0)
提交回复
热议问题