How to insert new row into table at a certain index using jQuery?


To insert a new row into table at a certain index, use the jQuery val() and insertBefore() method. You can try to run the following code to learn how to insert new row into table −

Example

Live Demo

<html>
  <head>
  <title>jQuery Example</title>
  <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
  $(document).ready(function(){          
    $('#index').val($('#myTable tbody tr').length);
    $('#btn1').click(function(){
      var indx = $('#index').val()-1;
      var newRow = $('<tr><td>New row is added at index '+$('#myTable tbody tr').length+'</td></tr>');
      newRow.insertBefore($('#myTable tbody tr:nth('+indx+')'));
   });
  });
</script>
</head>
<body>
  <table id="myTable">
    <tbody>
     <tr>
      <td>This is row 1</td>
     </tr>
     <tr>
      <td>This is row 2</td>
     </tr>
    </tbody>
  </table>
  <input id="index"/>
  <button type="button" id="btn1">Add</button>
</body>
</html>

Updated on: 20-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements