Home > Software design >  How to duplicate a row of table inputs in JavaScript?
How to duplicate a row of table inputs in JavaScript?

Time:07-27

Coding newbie here, basically I want to be able to duplicate a row of inputs so the user can add as many as they like. I’ve managed to get it to add a new row, but they’re not input boxes and they’re just floating out of place. They should also go to the bottom of the table.

Before click: Before click

After click: After click

HTML
<div  onl oad="createTable()">
<h2>Goals</h2>
<table id="goalsTable">
  <tbody>
  <tr>
    <td><input type="text" placeholder="Name">: £<input type="number" placeholder="Amount"></td>
  </tr>
  </tbody>
</table><br>
<input type="button" onclick="addRow()" value="Add row">
JavaScript
function addRow() {
var x = document.getElementById("goalsTable").insertRow(0);
var y = x.insertCell(0);
var z = x.insertCell(1);
y.innerHTML = "Name";
z.innerHTML = "Amount";
}

CodePudding user response:

You can clone the existing last row and insert the clone after the original row:

const rows = document.getElementById('goalsTable').rows
const lastRow = rows[rows.length - 1]
lastRow.after(lastRow.cloneNode(true))

If you want to have a "template row" that won't be visible in the table and used only for creating new rows, wrap it in <template> and refer to the row inside of the template instead of the first table row to clone it:

<template id="template-row">
  <tr>(Put your template row here...)</tr>
</template>
const templateRow = document.getElementById('template-row').content.firstElementChild
const newRow = templateRow.cloneNode(true)
document.querySelector('#goalsTable tbody').appendChild(newRow)

CodePudding user response:

why don't you just use innerHTML:

function addRow(){

let tableBody = document.querySelector('#goalsTable tbody')
tableBody.innerHTML  =`<td><input type="text" placeholder="Name">: £<input type="number" placeholder="Amount"></td>`;
}

CodePudding user response:

On the click of Button, in the function addRow(), please try below sample code. Make sure you have used AJAX library

    var rowCount = $('#goalsTable tr').length;
            var $lastRow = $("[id$=goalsTable] tr:last-child");
            var $newRow = $lastRow.clone(); //clone it
$lastRow.after($newRow);
  • Related