Home > database >  Add a row below a specific row
Add a row below a specific row

Time:03-01

I want to add a row below another but it is added at the end.

<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <table style="width: 200px" border="1">
      <tr>
        <th style="width: 100px">A</th>
        <th style="width: 100px">B</th>
      </tr>
      <tr id="info">
        <td>Data1</td>
        <td>Data2</td>
      </tr>
      <tr>
        <th colspan="2">C</th>
      </tr>
    </table>
    <br />
    <button type="button" onclick="AddRow()">Add Row</button>
  </body>
</html>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  function AddRow() {
    $('#info').parent().append('<tr><td>Data3</td><td>Data4</td></tr>');
  }
</script>

I would like it to be added as follows. Is there a way to achieve this?

demo

CodePudding user response:

The parent of tr#info is the table itself. Therefore when you append() to that table the content is placed at the end.

To do what you require select #info and use after() to insert the content directly after the target:

jQuery($ => {
  $('.add-row').on('click', () => {
    $('#info').after('<tr><td>Data3</td><td>Data4</td></tr>');
  });
});
table { width: 200px; }
th { width: 100px; }
<table border="1">
  <tr>
    <th>A</th>
    <th>B</th>
  </tr>
  <tr id="info">
    <td>Data1</td>
    <td>Data2</td>
  </tr>
  <tr>
    <th colspan="2">C</th>
  </tr>
</table><br />

<button type="button" >Add Row</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Also note in the example above that I moved the inline CSS to an external stylesheet and the inline JS event handler to an unobtrusive one attached via jQuery. Your HTML should ideally contain no code other than HTML.

CodePudding user response:

You should use jQuery after() function - https://api.jquery.com/after/

Example:

<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <table style="width: 200px" border="1">
      <tr>
        <th style="width: 100px">A</th>
        <th style="width: 100px">B</th>
      </tr>
      <tr id="info">
        <td>Data1</td>
        <td>Data2</td>
      </tr>
      <tr>
        <th colspan="2">C</th>
      </tr>
    </table>
    <br />
    <button type="button" onclick="AddRow()">Add Row</button>
  </body>
</html>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  function AddRow() {
    $('#info').after('<tr><td>Data3</td><td>Data4</td></tr>');
  }
</script>

  • Related