How to duplicate rows with empty textareas using JavaScript?

I’m working on a feature to add new rows to a table using JavaScript. The cloning part works fine but I’m running into a problem. When I’m on the edit page the cloned row copies the textarea content from the original row. I want the new textareas to be empty instead.

Here’s a simplified version of my code:

function copyRow(element) {
  const table = element.closest('table');
  const lastRow = table.rows[table.rows.length - 1];
  const newRow = lastRow.cloneNode(true);
  
  const inputs = newRow.querySelectorAll('input, select, textarea');
  inputs.forEach(input => {
    if (input.tagName === 'TEXTAREA') {
      input.value = '';
    } else if (input.type === 'text' || input.tagName === 'SELECT') {
      input.value = input.defaultValue;
    }
  });
  
  table.appendChild(newRow);
}

This function clones the last row of the table but I can’t figure out how to clear the textarea values. Any ideas on how to fix this? Thanks for your help!

I ran into a similar issue when working on a dynamic form generator. What worked for me was using the defaultValue property instead of value or innerHTML. Here’s what I’d suggest:

input.defaultValue = ‘’;

This approach ensures that the textarea starts empty but doesn’t interfere with any potential form reset functionality. Also, make sure you’re not accidentally cloning any event listeners that might be repopulating the textareas.

If that doesn’t solve it, you might want to check if there’s any JavaScript running after the cloning that’s filling in the textareas. Sometimes framework-specific behaviors can cause unexpected results. In my case, I had to add a small delay before clearing the values to ensure all framework processes had completed.

Let us know if this helps or if you need more troubleshooting!

I’ve encountered this issue before, and I can suggest a solution that worked in my project. Instead of using input.value = '', try using input.textContent = ''. This approach directly targets the content of the textarea element. Here’s how you could modify your code:

inputs.forEach(input => {
  if (input.tagName === 'TEXTAREA') {
    input.textContent = '';
  } else if (input.type === 'text' || input.tagName === 'SELECT') {
    input.value = input.defaultValue;
  }
});

This method should effectively clear the content of the cloned textareas. If you’re still experiencing issues, consider checking if there are any event listeners or scripts that might be populating the textareas after cloning.

hey tom, i had a similar issue. try setting the innerHTML of the textarea to an empty string instead of using value. like this:

input.innerHTML = ‘’;

that worked for me. hope it helps! let me know if u still have trouble