1

Is there any way to insert a row on a specific place in the table. The user will input a number where he/she wants the row to be inserted.

Let's say that the user wants the row to be inserted on the second row of the tbody of the table.

<tr>
    <td>00001</td>
    <td>John</td>
</tr>

The table I have

<tr>
    <td>00002</td>
    <td>David</td>
</tr>
        <!-- Here is where I want it to be insterted -->
<tr>
    <td>00004</td>
    <td>Frank</td>
</tr>
<tr>
    <td>00005</td>
    <td>Jane</td>
</tr>
AyakoS
  • 221
  • 2
  • 7
  • 18

3 Answers3

1

You can use the method after to insert html, and to insert in the right place you can use CSS pseudo-class :nth-child

$("table > tbody > tr:nth-child(2)").after('<tr><td>Example</td></tr>');

In my example you insert after the second tr tag.

R3tep
  • 12,512
  • 10
  • 48
  • 75
  • 1
    That is wrong. The code insert html into target `tr`. You should use `.after()` instead of `.append()` – Mohammad Mar 06 '17 at 13:45
0

You can select the tr:first element and than .after() to add your new element:

$('table tr:first').after('<tr><td>00001</td><td>John</td></tr>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr>
    <td>00002</td>
    <td>David</td>
  </tr>
  <!-- Here is where I want it to be insterted -->
  <tr>
    <td>00004</td>
    <td>Frank</td>
  </tr>
  <tr>
    <td>00005</td>
    <td>Jane</td>
  </tr>
</table>
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
0

An approach could be by adding a method in jquery prototype object for example:

// a method to add row after specific row
$.prototype.addTableRowAfter = function(row, element) {
  // here you can modify it to a more general approach
  this.find('tr:eq(' + row + ')').after(element);
  return this;
};

// call it
$('table').addTableRowAfter(0, '<tr><td> 00001</td><td>John</td ></tr>');
$('table').addTableRowAfter(2, '<tr><td> 00003</td><td>Jim</td ></tr>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>00002</td>
      <td>David</td>
    </tr>
    <!-- Here is where I want it to be insterted -->
    <tr>
      <td>00004</td>
      <td>Frank</td>
    </tr>
    <tr>
      <td>00005</td>
      <td>Jane</td>
    </tr>
  </tbody>
</table>
Alex Char
  • 32,879
  • 9
  • 49
  • 70