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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay