JSFiddle - React, Tailwind, and code Playground

by Twisty

HTML

<table id="sortFixed" class="grid">
  <caption>Kurt Vonnegut novels</caption>
  <thead>
    <tr>
      <th>Order</th>
      <th>Year</th>
      <th>Title</th>
      <th>Grade</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="text" id='ordem_0' name="order"></td>
      <td>1969</td>
      <td>Slaughterhouse-Five</td>
      <td>A+</td>
    </tr>
    <tr>
      <td><input type="text" id='ordem_1' name="order"></td>
      <td>1952</td>
      <td>Player Piano</td>
      <td>B</td>
    </tr>
    <tr>
      <td><input type="text" id='ordem_2' name="order"></td>
      <td>1963</td>
      <td>Cat's Cradle</td>
      <td>A+</td>
    </tr>
    <tr>
      <td><input type="text" id='ordem_3' name="order"></td>
      <td>1973</td>
      <td>Breakfast of Champions</td>
      <td>C</td>
    </tr>
    <tr>
      <td><input type="text" id='ordem_4' name="order"></td>
      <td>1965</td>
      <td>God Bless You, Mr. Rosewater</td>
      <td>A</td>
    </tr>
  </tbody>
</table>

JavaScript

$(function() {
  function showIndex(tb) {
    var fields = $(tb).find("input[name='order']");
    console.log(fields);
    fields.each(function(ind, el) {
      console.log(ind, el);
      $(el).val(ind + 1);
    });
  }

  function spliceRow(tb, r, i) {
    var ind = i - 1;
    var ln = $("tr", tb).length;
    var rows = [];
    $("tr", tb).each(function(ind, el) {
      rows.push(el);
    });
    rows.splice(ind, 0, r);
    tb.html("");
    $.each(rows, function(k, v) {
      tb.append(v);
    });
  }
  // Fix the width of the cells
  $('td, th', '#sortFixed').each(function() {
    var cell = $(this);
    cell.width(cell.width());
  });

  $('#sortFixed tbody').sortable({
    items: "> tr",
    update: function(e, ui) {
      console.log("Sort Update.");
      showIndex($(this));
    }
  }).disableSelection();

  $("#sortFixed tbody").on("change", "input[name='order']", function(e) {
    var me = $(this);
    var orig = me.parents("tr");
    var row = orig.clone();
    var t = parseInt(me.val());
    console.log(t, row);
    orig.remove();
    spliceRow($("#sortFixed tbody"), row, t);
    $("#sortFixed tbody").sortable("refresh");
    showIndex($("#sortFixed tbody"));
  });
});