Home » Jquery » javascript – Changing table row order using buttons not working every time

javascript – Changing table row order using buttons not working every time

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a table with 2 <tr>‘s per project, .project-row & .expandable-row. I’m trying to change the order of these projects using up/down buttons in .project-row, which I got to work, but not 100% of the time:

JSFiddle

For example: when I click down on project 1, it moves down as expected, but when I try to move it down again, I have to click it twice before it actually moves.

Why?

How to&Answer:

The issue is because your chained use of next() and prev() is targeting the wrong rows – it goes to the middle of the target group instead of before/after it.

You can fix this and make the logic simpler by combining the event handlers which move the content and change their behaviour based on some data attributes. Try this:

jQuery(function($) {
  $(document).on('click', '.order-change', function() {
    $('.expandable-row').hide();
    
    var $trigger = $(this)
    var $row = $trigger.closest('tr');
    var $infoRow = $row.next('tr');

    if ($trigger.data('dir') === 'up') {
      $row.add($infoRow).insertBefore($row.prev());
    } else {
      $row.add($infoRow).insertAfter($infoRow.next());
    }
  });
});
td {
  border: 1px solid black;
  text-align: center;
}

td div {
  cursor: pointer;
}

.expandable-row {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr class="project-row" data-project-id="0">
      <td>
        <div class="order-change" data-dir="up">up</div>
        <div class="order-change" data-dir="down">down</div>
      </td>
      <td>Project 1</td>
    </tr>
    <tr class="expandable-row" data-project-id="0">
      <td>Project 1 info</td>
    </tr>
    <tr class="project-row" data-project-id="1">
      <td>
        <div class="order-change" data-dir="up">up</div>
        <div class="order-change" data-dir="down">down</div>
      </td>
      <td>Project 2</td>
    </tr>
    <tr class="expandable-row" data-project-id="1">
      <td>Project 2 info</td>
    </tr>
    <tr class="project-row" data-project-id="2">
      <td>
        <div class="order-change" data-dir="up">up</div>
        <div class="order-change" data-dir="down">down</div>
      </td>
      <td>Project 3</td>
    </tr>
    <tr class="expandable-row" data-project-id="2">
      <td>Project 3 info</td>
    </tr>
  </tbody>
</table>