0

So i wanna have a table with 3 rows and next to every row is a button that makes the row go one row up but idk how to doit

table:

<table id="Tabelle1">
            <thead>
                <th></th>
                <th>ID</th>
                <th>NAME</th>
                <th>Nachname</th>
            </thead>
            <tbody>
                <tr>
                    <td><input type="button" value="oben"></td>
                <td>1</td>
                <td>Davin</td>
                <td>Humburg</td>
            </tr>
            <tr>
                <td><input type="button" value="oben"></td>
                <td>David</td>
                <td>Hamburg</td>
            </tr>
            <tr>
                <td><input type="button" value="oben"></td>
                <td>2</td>
                <td>3</td>
                <td>4</td>
            </tr>
            </tbody>
        </table>

Script:

$(document).ready(function() {
        $("#Tabelle1 input.oben").live("click", function() {
            var tr = $(this).closest("tr").remove().clone();
            tr.find("input.^")
            
        })
Entex
  • 5
  • 3
  • Does this answer your question? [How to move an element into another element?](https://stackoverflow.com/questions/1279957/how-to-move-an-element-into-another-element) – Chris Sep 06 '21 at 15:06

1 Answers1

0

Here's some changes to get your code working:

  • .live is deprecated. You could use event delegation $(document).on("click", "input.oben"... but with the following changes, no need as the elements remain.
  • input.oben .oben is a class selector so your inputs need class="oben" or use an attribute selector - classes are easier
  • you can move the element with tr.insertBefore(tr.prev()); as jquery DOM insert/appends will move existing elements, so no need for .remove/.clone
  • you'll need an edge case for the top row, easiest is a bit of css to hide the button on the top row

Given your original HTML (no changes to the HTML other than value= / class= here's an updated snippet:

$(document).ready(function() {
  $("#Tabelle1 input.oben").on("click", function() {
    var tr = $(this).closest("tr");
    tr.insertBefore(tr.prev());
  })
});
#Tabelle1 tr:first-child input.oben { display:none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="Tabelle1">
  <thead>
    <th></th>
    <th>ID</th>
    <th>NAME</th>
    <th>Nachname</th>
  </thead>
  <tbody>
    <tr>
      <td><input type="button" class="oben" value='^'></td>
      <td>1</td>
      <td>Davin</td>
      <td>Humburg</td>
    </tr>
    <tr>
      <td><input type="button" class="oben" value='^'></td>
      <td>David</td>
      <td>Hamburg</td>
    </tr>
    <tr>
      <td><input type="button" class="oben" value='^'></td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
    </tr>
  </tbody>
</table>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57