Add and Remove table rows
HTML / JavaScript / jQuery

How to Add and Remove table rows dynamically using jQuery

Add and Remove table rows

Hi, today we will learn about how to add and remove table rows dynamically using jQuery. I will tell you everything in details about it to make you understand.

Note: I will not write css for styling the table or buttons. I will only focus on the functionality to make sure you get better understanding about it.

What we are going to create

First we will create a basic table with an id and it’s value will be my_table two columns which will contain a nested table.

<table id="my_table"></table>

Now we will create a row in our table with three columns like the given example.

<tr>
  <td>Name: </td>
  <td>
    <input type="text">
  </td>
  <td>
    <button type="button" class="remove_btn">Remove Row</button>
  </td>
</tr>

The above example will display Name, Input box and a Remove Row button. Now we need a Add Row button which should be outside the table. So first we add a <hr> tag after the closing </table> tag to separate table and the Add Row button. Then we create a Add Row button like the given example and your HTML is ready to make the functionality of add/remove rows.

<table id="my_table">
  <tr>
    <td>Name: </td>
    <td>
      <input type="text">
    </td>
    <td>
      <button type="button" class="remove_btn">Remove Row</button>
    </td>
  </tr>
</table>
<hr/>
<button class="add_btn">Add Row</button>

First include jQuery after closing the </body> tag. Then add the below given code. It make add the functionality of adding the rows by clicking on the Add Row button.

$(document).on('click', '.add_btn', function() {
  var tr = $('#my_table tr').first().clone();
  $('#my_table').append(tr);
});

Note: .append(tr) will add row after the last row in the table. In case you want add the row in the beginning of all rows then replace the .append(tr) to .prepend(tr).

Now we will add Remove Row functionality but we have to make sure that if there is only one row in the table then Remove Row button should not work. So to do this we will add the given below.

$(document).on('click', '.remove_btn', function() {
  if($('#my_table tr').length == 1) {
    return false;
  }else{
    $(this).closest('tr').remove();
  }
});

The above code will first check that if there is only single row in the table then it return false and if there are rows more than 1 then it will remove the clicked row from the table.

Thanks for visiting.

Author

I am a Full Stack Web Developer. I have more than 8 years of experience in the web design and development industry.

Leave a Reply

Your email address will not be published. Required fields are marked *