Create Clone of Table Row and Append to Table in JavaScript

Create clone of table row and append to table in JavaScript

If you don't wish to use jQuery, there are a couple of simple functions you could use, like cloneNode(), createElement() and appendChild(). Here is a simple demonstration that appends a row to the end of the table using either the clone or create method. Tested in IE8 and FF3.5.

<html>
<head> <script type="text/javascript"> function cloneRow() { var row = document.getElementById("rowToClone"); // find row to copy var table = document.getElementById("tableToModify"); // find table to append to var clone = row.cloneNode(true); // copy children too clone.id = "newID"; // change id or other attributes/contents table.appendChild(clone); // add new row to end of table }
function createRow() { var row = document.createElement('tr'); // create row node var col = document.createElement('td'); // create column node var col2 = document.createElement('td'); // create second column node row.appendChild(col); // append first column to row row.appendChild(col2); // append second column to row col.innerHTML = "qwe"; // put data in first column col2.innerHTML = "rty"; // put data in second column var table = document.getElementById("tableToModify"); // find table to append to table.appendChild(row); // append row to table } </script></head>
<body> <input type="button" onclick="cloneRow()" value="Clone Row" /> <input type="button" onclick="createRow()" value="Create Row" /> <table> <tbody id="tableToModify"> <tr id="rowToClone"> <td>foo</td> <td>bar</td> </tr> </tbody> </table></body>
</html>

How to clone a <tr> in a table with Javascript

When using methods such as cloneNode(), or createElement() you'll need to append the new node to the DOM or it'll just float around aimlessly. Also, when cloning a node, keep in mind that if it and/or its children have any #ids, you'll end up having duplicated #ids which is super invalid. You should either change the #ids on all clones or do away with #ids on cloned nodes and use classes, tags, attributes, etc. instead.

In this demo, I replaced the form controls' #ids with name attribute since that's all you need to have in order to submit values from a <form> to a server (that and a <input type='submit'> button of course).

Demo

function addSelect() {
var T = document.getElementById('xTable');

var R = document.querySelectorAll('tbody .row')[0];

var C = R.cloneNode(true);

T.appendChild(C);

}
<form id="frm1" action="Calculate.html">
<table id="xTable">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
</tr>
</thead>
<tr class="row">
<td>
<select name="products">
<option value="80">Product-A</option>
<option value="80">Product-B</option>
<option value="80">Product-C</option>
<option value="80">Product-D</option>
<option value="16">Product-E</option>
</select>
</td>
<td><input type="number" name="ndc" placeholder=""></td>
<td>
<p id="ndpc"></p>
</td>
<td>
<p id="pu"></p>
</td>
<td>
<p id="ptpp"></p>
</td>
</tr>
</table>


<input type="button" onclick="addSelect()" value="Add">
</form>

Appending a cloned row of a table to a specified position on table

Do not use id="tablerow" as duplicate ids will cause malformed HTML.

Change <tr id="tablerow"> in your string to just <tr>

Script

function addRow() {
var referenceNodes = document.getElementById("dataTable").getElementsByTagName("tr");
//-2 because last row is button row
var referenceNode = referenceNodes[referenceNodes.length - 2];
var newNode = referenceNode.cloneNode(true);
newNode.getElementsByTagName("input")[0].checked = false;
newNode.getElementsByTagName("input")[1].value = "";
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

Demo: http://jsfiddle.net/naveen/wbFMm/

Copy table row without values

With jQuery you could do the following:

$("table").append($("table")
.find("#gonnaclone").clone()
.find("input").val("").end());

What this actually does is make a clone, find the input fields, reset the input value and append it to the table.

But to make it even better you should also remove the ID of the cloned row (otherwise you would have duplicate IDs):

$("table").append($("table")
.find("#gonnaclone").clone().removeAttr("id")
.find("input").val("").end());

A complete example can be found on JSFiddle.


If you also want to force the checkbox to be in a certain state (checked/unchecked) you could even make a bigger chain:

$("table").append($("table")
.find("#gonnaclone").clone().removeAttr("id")
.find("input").val("").end()
.find("input:checked").attr("checked", false).end());

This actually unchecks the cloned row.

How can i Clone a Table Row and append it to a Table?

Remove the $ before your variables. Use the variable as you have declared it.. Either with or without $ but use the same name.

$(document).ready(function() {  var add_button = $('#add_new');  var blank_row = $('#blank_row');  var time_table = $('#time_table');
add_button.click(function() { blank_row.clone().appendTo(time_table); });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table id="time_table">  <tr>    <th>Last Name</th>    <th>First Name</th>    <th>Rate</th>    <th class="time">ST</th>    <th class="time">TH</th>    <th class="time">DT</th>    <th class="time">EX-ST</th>    <th class="time">EX-TH</th>    <th class="time">EX-DT</th>  </tr>  <tr id="blank_row">    <td><input type="text" name="last_name"></td>    <td><input type="text" name="first_name"></td>    <td><input type="text" name="rate"></td>    <td><input type="number" name="st" class="time_input"></td>    <td><input type="number" name="th" class="time_input"></td>    <td><input type="number" name="dt" class="time_input"></td>    <td><input type="number" name="ex_st" class="time_input"></td>    <td><input type="number" name="ex_th" class="time_input"></td>    <td><input type="number" name="ex_dt" class="time_input"></td>  </tr></table>
<button id="add_new">Button</button>

How to clone and append a table row

In what you tried, you forgot to include the # before the ID, that's why it didn't work, but still it would've appended the entire element to itself, causing all sorts of issues.

What you need to clone is the first <tr>.

$(function() {
var $componentTB = $("#component_tb"),
$firstTRCopy = $componentTB.children('tr').first().clone();
$("#addRows").click(function() {
$componentTB.append($firstTRCopy.clone());
});
});

The double-.clone() is needed because the element stored in $firstTRCopy would get appended permanently otherwise, and in case it's removed from the DOM, you'll not get anything when you try to append it again. This way, it can be cloned every time it's needed.


In your code you have a text input with the ID component_thickness. While this code in itself will not cause duplicate IDs to appear, you will need to edit that input and get rid of the ID, probably making it a class.

Clone Table Row with drop down not working

Try This
There will be many changes needed in your code ..

  1. you wrote $("CloneButton").click(function() { - it misses the # ID selector - so your button click will not fire. You need to write $("#CloneButton").click(function() {
  2. You need to set selectd attribute for both dropdown before you clone and append. You can set selected attribute using .attr("selected", true)

Below code is working fine for me. Check Working Code Snippet

$("#CloneButton").click(function() {
var drp1Value = $('#rowtemplate tr').find('select').eq(0).val();$("option[value=" + drp1Value + "]", $('#rowtemplate tr').find('select').eq(0)) .attr("selected", true).siblings() .removeAttr("selected");
var drp2Value = $('#rowtemplate tr').find('select').eq(1).val();
$("option[value=" + drp2Value + "]", $('#rowtemplate tr').find('select').eq(1)) .attr("selected", true).siblings() .removeAttr("selected");


var clonedRow = $('#rowtemplate tr').clone(); $('#Maintable').append(clonedRow); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><h4 >Main Table</h4>
<table id="Maintable" ><th>Client</th><th>Heading</th><th>Heading</th><th>Total</th><th>Delete?</th><tr> <td><span class="project"> <select class="form-control projectcodeid" id="Records_0__SelectedProjectFromList" name="Records[0].SelectedProjectFromList"><option value="">Modeling</option><option value="1">Ventosanzap</option><option value="2">Modeling</option><option value="3">Xilinx ISE</option></select></span> </td> <td> <input type="hidden" name="Records.Index" value="0"> <span class="billingcodeCss"> <select class="form-control timecodeDdlId" id="Records_0__SelectedBillingCodesFromList" name="Records[0].SelectedBillingCodesFromList"> <option value="">Budget-070</option> <option selected="selected" value="5">Budget-070</option> <option value="6">Budget-784</option> <option value="7">Cost Center-027</option> </select></span> </td> <td> <input name="Records[0].TimeRecords[0].ID" type="hidden" value=""> <input class="meters" name="Records[0].TimeRecords[0].Meters" type="text" value=""> </td> <td class="rowtotal">10.00</td>
<td> <input class="bs-checkbox mt-checkbox mt-checkbox-outline deleteRow" name="Records[0].DeleteRow" type="checkbox" value="true"><input name="Records[0].DeleteRow" type="hidden" value="false"> </td> </tr> <tr> <td><span class="project"> <select class="form-control projectcodeid" id="Records" name="Records[1].SelectedProjectFromList"><option value="">Xilinx ISE</option><option value="1">Ventosanzap</option><option value="2">Modeling</option><option value="3">Xilinx ISE</option>
</select></span> </td> <td> <input type="hidden" name="Records.Index" value="1"> <span class="billingcodeCss"> <select class="form-control timecodeDdlId" id="Records_1__SelectedBillingCodesFromList" name="Records[1].SelectedBillingCodesFromList"><option value="">Bill-727 </option><option value="1">TIME CODE A </option><option selected="selected" value="2">Bill-727 </option><option value="3">Bill-561 </option><option value="4">Bill-281 </option></select></span> </td> <td> <input name="Records[1].TimeRecords[0].ID" type="hidden" value=""> <input class="meters" name="Records[1].TimeRecords[0].Meters" type="text" value=""> </td> <!-- added row totals rowtotalmeters--> <td class="rowtotal"> 0.00 </td>
<td> <input class="bs-checkbox mt-checkbox mt-checkbox-outline deleteRow" name="Records[1].DeleteRow" type="checkbox" value="true"><input name="Records[1].DeleteRow" type="hidden" value="false"> </td> </tr> </table> <!--*********** End Main Table--> <hr /> <h4>Row template</h4> <button type="button" id="CloneButton">Add Clone Row to table!</button> <table id="rowtemplate"><tr> <td> <span class="project"> <select class="form-control projectcodeid" id="Records_0__SelectedProjectFromList" name="Records[0].SelectedProjectFromList"><option value="">Default</option> <option value="0">Null</option><option value="1">Ventosanzap</option><option value="2">Modeling</option><option value="3">Xilinx ISE</option></select></span> </td> <td> <input type="hidden" name="Records.Index" value="0"> <span class="billingcodeCss"> <select class="form-control timecodeDdlId" id="Records_0__SelectedBillingCodesFromList" name="Records[0].SelectedBillingCodesFromList"> <option value="">Default</option> <option value="0">Null</option> <option value="">Budget-070</option> <option value="5">Budget-070</option> <option value="6">Budget-784</option> <option value="7">Cost Center-027</option> </select></span> </td> <td> <input name="Records[0].TimeRecords[0].ID" type="hidden" value=""> <input class="meters" name="Records[0].TimeRecords[0].Meters" type="text" value=""> </td> <td class="rowtotal">0.00</td>
<td> <input class="bs-checkbox mt-checkbox mt-checkbox-outline deleteRow" name="Records[0].DeleteRow" type="checkbox" value="true"><input name="Records[0].DeleteRow" type="hidden" value="false"> </td> </tr>
</table>

Add & Remove Cells from Cloned Table Rows

You should try to attach your handlers with Javascript properly, not with inline handlers. Just add a single handler to the table, and when the X is clicked, remove the row by navigating upwards from the clicked button to the tr to remove:

$('table.group').on('click', '.group_remove', function() {  const tr = this.parentElement.parentElement;  tr.remove();});$('.add').on('click', function (){  const cloned = $('.group tr:last-child').clone();  $('.group').append(cloned);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table class='group'>  <tr class='group_row_0'>    <td>Thing 1</td>    <td>Thing 2</td>    <td>Thing 3</td>    <td>Thing 4</td>    <td>      <a href='#' class='group_remove'>X</a>    </td>  </tr>    <tr class='group_row_1'>    <td>Thing 1</td>    <td>Thing 2</td>    <td>Thing 3</td>    <td>Thing 4</td>    <td>      <a href='#' class='group_remove'>X</a>    </td>  </tr>    <tr class='group_row_2'>    <td>Thing 1</td>    <td>Thing 2</td>    <td>Thing 3</td>    <td>Thing 4</td>    <td>      <a href='#' class='group_remove'>X</a>    </td>  </tr>    <tr class='group_row_3'>    <td>Thing 1</td>    <td>Thing 2</td>    <td>Thing 3</td>    <td>Thing 4</td>    <td>      <a href='#' class='group_remove'>X</a>    </td>  </tr></table>
<div class="add">add row</div>

Copy table rows in multiple table using JQUERY

When you call:

var row = $('<tr/>');
tableFoo.append(row); // row created on tableFoo
tableBar.append(row); // row moved from tableFoo to tableBar

You are just moving the row around. Which means the row will end up in the last place you called .append(row).

You have that problem in several parts of your code. To fix it, instead of appending the recently-created row, append a clone of it, like:

tableFoo.append(row.clone()); // row created on tableFoo
tableBar.append(row.clone()); // row created on tableBar

Demo:

var Uncounted = 0;var countUnmatched = 0;var countMatched = 0;$.getJSON("https://api.myjson.com/bins/1h1yxz", function(data) {  var tableAll = $('#allCount tbody');  var tableUc = $('#Uncounted tbody');  var tableUm = $('#Unmatch tbody');  var tableMatched = $('#Matched tbody');  var count = data.length;  tableAll.empty();  tableUc.empty();  tableUm.empty();  tableMatched.empty();  $.each(data, function(i, v) {    var Desc = $('<td/>').append(v.Description);    var expCount = $('<td/>').append(v.ExpectedCount);    var total = $('<td/>').append(v.Total);    var discrepancy = $('<td/>').append(v.Discrepancy);    var cost = $('<td/>').append(v.Cost);    var row = $('<tr/>').append(Desc).append(expCount).append(total).append(discrepancy).append(cost);
if (v.Total == null || v.Total == '') { Uncounted++; tableUc.append(row.clone()); } if (parseFloat(v.ExpectedCount) !== parseFloat(v.Total)) { countUnmatched++; tableUm.append(row.clone()); } else { countMatched++; tableMatched.append(row.clone()); } tableAll.append(row.clone());
});});
table, tbody, tr, td { border: 1px solid black; border-collapse: collapse }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
allCount:<table id="allCount"> <tbody></tbody></table><br>Uncounted:<table id="Uncounted"> <tbody></tbody></table><br>Unmatch:<table id="Unmatch"> <tbody></tbody></table><br>Matched:<table id="Matched"> <tbody></tbody></table>

jQuery Duplicate Table row and assign new id to duplicate table row

Try next one:

 $(document).ready(function () {            $("#btn_AddTruck").click(function () {               var $tableBody = $('#tbl_invTruck').find("tbody"),                $trLast = $tableBody.find("tr:last"),                $trNew = $trLast.clone();                // Find by attribute 'id'                $trNew.find('[id]').each(function () {                    var num = this.id.replace(/\D/g, '');                    if (!num) {                        num = 0;                    }                    // Remove numbers by first regexp                    this.id = this.id.replace(/\d/g, '')                         // increment number                        + (1 + parseInt(num, 10));                });                        $trLast.after($trNew);                     });        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>    <div id="invTruck" class="invTruck">                <table id="tbl_invTruck" width="100%"  border="0">                <tbody>                    <tr>                        <td width="15%" style="display:none;"><center>Work Order Id</center></td>                        <td width="17%"><center>Truck Type</center></td>                        <td width="17%"><center>Licences Plate #</center></td>                        <td width="17%"><center>Driver ID</center></td>                        <td width="17%"><center>Max Haulage Weight</center></td>                        <td width="17%"><center>Job Number</center></td>                    </tr>
<tr> <td style="display:none;"><input name="wInv_work_Id" type="text"></td> <td><select id="invTru_Type" name="invTru_Type" onchange="getTruckPlates(this.value)"> <option disabled selected hidden value="">Select A Truck Type</option> <!-- %while(rsinvTru1.next()){%> <option><%=rsinvTru1.getString(1)%></option> <%}% --> </select> </td> <td><select id="invTru_LicensePlateNo" name="invTru_LicensePlateNo" required> <option disabled selected hidden value="">Select A Truck</option>
</select></td> <td><input name="driver_emp_Id" type="text"></td> <td><input name="invTru_MaxHw" type="text"></td> <td><input name="" type="text"></td> </tr> </tbody> </table> <table width="100%" height="50%" border="0"> <tr> <td width="50%"><input class="buttonCreateInv" id="btn_AddTruck" type="button" value="Add A Truck"></td> <td width="50%"><input class="buttonCreateInv" name="btn_RemoveTruck" type="button" value="Remove A Truck"></td> </tr> </table> </div>


Related Topics



Leave a reply



Submit