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>
3
  • Yes. yuo can with the help of jquery. Commented Mar 6, 2017 at 13:40
  • Please provide your code. What have you tried so far? Commented Mar 6, 2017 at 13:41
  • 1
    Possible duplicate of How do you append rows to a table using jQuery? Commented Mar 6, 2017 at 13:42

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That is wrong. The code insert html into target tr. You should use .after() instead of .append()
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>

Comments

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>

2 Comments

what if I wanted the row to be inserted as the first row of the table?
@AyakoS to do that: $('#table').prepend('<tr><td>00001</td><td>John</td></tr>');

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.