DEV Community

Ripon Uddin
Ripon Uddin

Posted on

Add Row (Clone)

Today, I will share a simple way to implement cloning and removing tr dynamically and how to keep the last tr without removing it.

*Requirements Below: *

  1. A Selector to append TR
  2. add/remove selector class
<table class="table table-hover">
      <thead>
         <tr>
            <th>Product </th>
            <th>Description</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody class="productServicesTbody">
            <tr>
                <td>
                   <input
                      type="text"
                      class="form-control"
                    />
                </td>

                <td>
                   <input
                      type="text"
                      class="form-control"
                   />
                </td>

                <td>
                    <button type="button" class="btn btn-primary btn-sm addTr">
                      Add
                    </button>

                   <button type="button" class="btn btn-danger btn-sm removeTr">
                      Delete
                    </button>
                </td>
             </tr>
         </tbody>
   </table>
Enter fullscreen mode Exit fullscreen mode

JS Code

$(document).ready(function() {
        $(document).on('click', '.addTr', function() {
            let $clone = $(this).closest('tr').clone();
            $clone.find('input').val('');

            $('.productServicesTbody').append($clone);
        });

        $(document).on('click', '.removeTr', function() {
            if ($('.productServicesTbody tr').length > 1) {
                $(this).closest('tr').remove();
            }
        });
    });
Enter fullscreen mode Exit fullscreen mode

Here .addTr is an add new tr button selector. And .removeTr is an add new tr button selector.

Please, let me know your queries in the comment section.

HappyCoding #Js #jQuery

Top comments (0)