Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display of up/down buttons in table row reordering

I am using this jsfiddle: http://jsfiddle.net/vaDkF/828/ (without the top and bottom option) to create a reordering table.

$(document).ready(function(){
    $(".up,.down").click(function(){
        var row = $(this).parents("tr:first");
        if ($(this).is(".up")) {
            row.insertBefore(row.prev());
        } else  {
            row.insertAfter(row.next());
        } 
       
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td>One</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr>
        <td>Two</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr>
        <td>Three</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr>
        <td>Four</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr>
        <td>Five</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
</table>

I would like to know if it is possible to have the up button disappear (display none) if it is the first row in the table, and the down button disappear if it is the last row in the table.

Thanks!

like image 338
Jessica C Avatar asked Jul 06 '16 19:07

Jessica C


1 Answers

You can use CSS for this, with first-child and last-child selectors:

tr:first-child .up, tr:last-child .down {
  display:none;
}

$(document).ready(function() {
  $(".up,.down").click(function() {
    var row = $(this).parents("tr:first");
    if ($(this).is(".up")) {
      row.insertBefore(row.prev());
    } else {
      row.insertAfter(row.next());
    }
  });
});
tr:first-child .up,
tr:last-child .down {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>One</td>
    <td>
      <a href="#" class="up">Up</a>
      <a href="#" class="down">Down</a>
    </td>
  </tr>
  <tr>
    <td>Two</td>
    <td>
      <a href="#" class="up">Up</a>
      <a href="#" class="down">Down</a>
    </td>
  </tr>
  <tr>
    <td>Three</td>
    <td>
      <a href="#" class="up">Up</a>
      <a href="#" class="down">Down</a>
    </td>
  </tr>
  <tr>
    <td>Four</td>
    <td>
      <a href="#" class="up">Up</a>
      <a href="#" class="down">Down</a>
    </td>
  </tr>
  <tr>
    <td>Five</td>
    <td>
      <a href="#" class="up">Up</a>
      <a href="#" class="down">Down</a>
    </td>
  </tr>
</table>

Updated Demo

like image 99
DaniP Avatar answered Sep 25 '22 02:09

DaniP