The ins and outs of duplicating and adding an empty element

Is it possible to add empty html rows dynamically?

I want to insert new html rows and clear their contents afterward.

To achieve this, I tried using the .html('') method but faced some issues.

My implementation looks like the following code snippet:

How can I add rows and then clear their content successfully?

Thank you!

$(document).ready(function() {
   $("table").on( "click", "tr", function() {
       $("table").append($(this).clone().html(' '));
   });
});
table {
border-collapse:collapse;}

td {
border:solid black 1px;
transition-duration:0.5s;
padding: 5px;
cursor:pointer;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>0</td>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
    </tr>
  </tbody>
</table>

Answer №1

Is there a simpler way to insert tr instead of going through the process of cloning and removing its HTML?

$("table").on( "click", "tr", function() {
   $(this).after("<tr />");
});

If you also want to clone the td, you can try this approach:

$("table").on( "click", "tr", function() {
   var row = $(this).clone().find('td').html('');
   $(this).after(row);
});

If your goal is to add the cloned element at the end of the table, you can use this method:

$("table").on( "click", "tr", function() {
   var row = $(this).clone().find('td').html('');
   row.appendTo('table');
});

You could even simplify it to:

$('table').append(row)

In summary, make sure you are clearing the correct elements when working with cloned elements, like the td content instead of the entire clone.

Answer №2

$(document).ready(function() {
  var table=$("table");
  table.on( "click", "tr", function() {
       var clonedTr=$(this).clone();
       clonedTr.find("td").html("");
       table.append(clonedTr);
   });
});
table {
border-collapse:collapse;}

td {
border:solid black 1px;
transition-duration:0.5s;
padding: 5px;
cursor:pointer;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>0</td>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
    </tr>
  </tbody>
</table>

Answer №3

Check out this solution:

$( document ).ready(function() {
  $('#tableID').on( "click", "tr", function() {
    var elt = $(this).clone()
    elt.find('td').empty()
    $('#tableID').append(elt)
  })
});
    table td {
      border: 1px solid;
      }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableID">
  <tbody>
    <tr>
      <td>0</td>
      <td>1</td>
      <td>2</td>
    </tr>
  </tbody>
</table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switch the checkbox attribute for multiple items within a carousel using Angular 2/Typescript

I am currently working on a carousel feature where each item has a checkbox above it. My goal is to be able to click on an item and have its corresponding checkbox checked. The current code successfully achieves this, but the issue I'm facing is that ...

Delete specific rows within a grid view exclusively on the user's browser

I need to implement a feature where users can remove individual rows from a gridview on the screen without affecting the database. The gridview is populated based on the index selected from a dropdown list. Each row in the gridview should have a remove bu ...

What is the best way to include my PHP session variable within my JavaScript code?

i have a dynamic table that the enables to perform CRUD operations on a database. after logging in the user is directed to index.php, here a table is displayed with values stored in the database table "ajaxtable". i have joined "ajaxtable" table and "membe ...

How to retrieve the value from an editable td within a table using Jquery

I am working with a dynamic table that looks like this: <table> <tbody> <tr> <td>1</td> <td contenteditable='true'>Value1</td> </tr> <tr> ...

What is the functioning of the node.js next() middleware without any parameters supplied?

When working with middleware functions in Express, the signature typically includes function (req, res, next). However, it may be surprising to some that the next() call does not require any arguments. This concept can be better understood by considering t ...

The navigation bar is not staying fixed

Having trouble with the Bootstrap navbar-fixed-top feature. I have not applied any other styling to the nav element and have even tried adjusting z-index values with no success. <header> <nav class="navbar navbar-fixed-top navbar-expand-l ...

Revamp List Model through Ajax Integration in ASP .NET MVC5

Could someone please provide a hint on how to update the Model list in the view page after calling the Action Result with an Ajax request? Specifically, how can I refresh the current list model with the result of the Ajax call back? Here is the code for m ...

Experience the power of VueJS 3 with Pinia, all without the need

I've hit a wall. Despite scouring documentation and countless google searches, I can't seem to find the answer to this straightforward query: how do I install/import PINIA in a VUE application? Let's consider a basic VUE app: <div id=&qu ...

JavaScript - Retrieve a nested property within an object using an array of strings

I possess an object in the following format { metadata: { correlationId: 'b24e9f21-6977-4553-abc7-416f8ed2da2d',   createdDateTime: '2021-06-15T16:46:24.247Z' } } and I possess an array containing the properties I wish to re ...

React Native NavigationStack encountering mismatched screen component types

Currently, I am in the process of developing an app using React Native and React Navigation, utilizing TypeScript. One important step I took was creating a type called RootStackParams for my routes as shown below: App.tsx export type RootStackParams = { ...

What is the best way to retrieve information from a json file using axios in a React project?

I'm having trouble retrieving JSON data. { ID string `json:"id"` Amount int `json:"amount"` Month string `json:"month"` PayFailed bool `json:"pay_failed"` } I’ve written the foll ...

Implement a new functionality in a VUE.js loop using v-for for the href attribute

Looking to incorporate a link within a v-for loop using VUE.js, where the number of items ranges from 1 to 5. The catch is that the href attribute must be populated by a web api call to determine the URL. Below is the code snippet: <d ...

Using Vue.js to alter the CSS class property

I am exploring Vue.js and looking to modify a CSS class property. Here is the HTML code utilizing the specified class: <div class="customTimer"></div> Here is the corresponding CSS code: .customTimer { width: 100%; height: 1 ...

Performing live search with JQuery Ajax on two different types of fields - text input and dropdown select

Successfully implemented jQuery AJAX live search on an input field, returning desired results. Now aiming to create a compound search involving two fields. Current setup not yielding any results or errors: Form: <div class="form-group"> <div ...

Having trouble accessing data in Laravel and Vue JS views

I'm currently working on displaying table data in a view using Vue.js and Laravel. Here is what I have attempted so far: This is the comment controller: public function index() { $comment = Comment::Latest()->paginate(10); return new Comm ...

Combining Custom JQuery with Nested JQuery UI Tabs

Currently, I am using the Slate Wordpress theme which includes shortcodes for tabs powered by jquery.tabs.min.js. However, I encountered a problem when trying to nest tabs using the theme's shortcodes. To solve this issue, I decided to create my own ...

Combining properties from one array with another in typescript: A step-by-step guide

My goal is to iterate through an array and add specific properties to another array. Here is the initial array: const data = [ { "id":"001", "name":"John Doe", "city":"New York&quo ...

Create allowances for specific areas

One of my methods involves the saving of an author using the .findOneAndUpdate function. The structure of AuthorInterface is as follows: export interface AuthorInterface { name: string, bio: string, githubLink: string, ...

What could be causing this jQuery loop to not trigger consistently?

On my page, I have a product category in Woocommerce with 12 products. Each product includes a quantity field, and upon clicking a button at the bottom of the page, the script loops through the products to add any item to the cart if its quantity is greate ...

My attempt at creating a straightforward sorting function turned out to be ineffective

My attempt at creating a basic sorting function seems to be failing as it is still returning the original list instead of the sorted one. function sortByPopular (collection) { let items = collection.slice(); items.sort(function(a,b) { re ...