[Solved] Up and Down rows from table


Just change appendTo() to insertBefore() and insertAfter()

$(document).ready(function() {
  $("#table1 tbody tr").click(function() {
    $(this).toggleClass('selected');
  });
});

$(document).ready(function() {
  $("#table2 tbody tr").click(function() {
    $(this).toggleClass('selected');
  });
});

$(document).ready(function() {
  $(".down").click(function() {
    $('#table1 tr').each(function() {
      if ($(this).attr('class') == 'selected') {
        $(this).insertAfter($(this).nextAll(':not(.selected)').eq(0));
      }
    });
  });
});

$(document).ready(function() {
  $(".up").click(function() {
    $('#table1 tr').each(function() {
      if ($(this).attr('class') == 'selected') {
        $(this).insertBefore($(this).prevAll(':not(.selected)').eq(0));
      }
    });
  });
});
.selected {
  background-color: #F00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="up">UP</button>
<button type="button" class="down">DOWN</button>
<h2>Table1</h2>
<table id="table1">
  <tr>
    <td>Row1</td>
  </tr>
  <tr>
    <td>Row2</td>
  </tr>
  <tr>
    <td>Row3</td>
  </tr>
  <tr>
    <td>Row4</td>
  </tr>
  <tr>
    <td>Row5</td>
  </tr>
  <tr>
    <td>Row6</td>
  </tr>
</table>
<h2>Table2</h2>
<table id="table2">
  <tr>
    <td>Row21</td>
  </tr>
  <tr>
    <td>Row22</td>
  </tr>
  <tr>
    <td>Row23</td>
  </tr>
  <tr>
    <td>Row24</td>
  </tr>
  <tr>
    <td>Row25</td>
  </tr>
  <tr>
    <td>Row26</td>
  </tr>
</table>

Edit

Quick fix for problem of selected two next to each other

change this $(this).insertBofer($(this).prev()); to $(this).insertBefore($(this).prevAll(':not(.selected)').eq(0));

(Updated snippet)

6

solved Up and Down rows from table