Clone table and display after button - javascript

Great day Community,i'm facing clone whole table problem, if it have solution of clone several row it will be helping a lots.
If using document.getElementsByTagName("table")[2]; it can clone the table and put it in body because i'm using document.body.appendChild(myClone) to do it.
Here is some code:
Solution 1:
function myFunction() {
myTable = document.getElementsByTagName("table")[2]; // doesn't use any table id
myClone = myTable.cloneNode(true);
var y = document.body.appendChild(myClone);
}
Solution 2:
function myFunction() {
var x = document.getElementById("0"); // using this to find auto genereate id for table
test = x.cloneNode(true);
}
Html Display:
<table>
<tr>
<td>
<table id="0">
<tr>
<td><span></span>Name:<input type="text" value="Tom"/> </td>
<td><span> </span>Age:<input type="text" value="25"/> </td>
<td><span> </span>Email:<input type="text" value="tom#gmail.com"/> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table id="1">
<tr>
<td><span></span>Name:<input type="text" value="Alice"/> </td>
<td><span> </span>Age:<input type="text" value="22"/> </td>
<td><span> </span>Email:<input type="text" value="alice#gmail.com"/> </td>
</tr>
</table>
<input type="button" onclick="myFunction()"/>
</td>
</tr>
</table>
Expected result clone the table after the button, the table inside will not have more than 5.
Please help thank you.

Although Dominic Amal Joe F's answer was on the right track, it had some flaws, as well as the structure of the OP table. I think this code would work properly:
function myFunction(){
// get main table body
var tableBody = document.getElementById('mytable').children[0];
// get existing rows
var rows = tableBody.children.length;
// clone the last row (which contains the last table)
var newRow = tableBody.children[rows-1].cloneNode(true);
// get the new row table
var newTable = newRow.children[0].children[0]
// change the table id
newTable.setAttribute('id', rows);
// reset the inputs values
var cells = newTable.children[0].children[0].children;
for (var i=0; i<cells.length; i++) {
cells[i].children[1].value = "";
}
// append the new row to the main table body
tableBody.appendChild(newRow);
}
<table id="mytable">
<tr>
<td>
<table id="0">
<tr>
<td><span>Name:</span><input type="text" value="Tom"/></td>
<td><span>Age:</span><input type="number" value="25"/></td>
<td><span>Email:</span><input type="email" value="tom#gmail.com"/></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table id="1">
<tr>
<td><span>Name:</span><input type="text" value="Alice"/></td>
<td><span>Age:</span><input type="number" value="22"/></td>
<td><span>Email:</span><input type="email" value="alice#gmail.com"/></td>
</tr>
</table>
</td>
</tr>
</table>
<button onclick="myFunction()">Clone</button>

I feel the following code will help you.
HTML
<table>
<button onclick="myFunction()">clone</button>
<tr>
<table id="parent-table">
<tr id="parent-row">
<td><span></span>Name:<input type="text" value="Tom"/> </td>
<td><span> </span>Age:<input type="text" value="25"/> </td>
<td><span> </span>Email:<input type="text" value="tom#gmail.com"/></td>
</tr>
</table>
</tr>
</table>
JavaScript
function myFunction(){
let parentTable = document.getElementById("parent-table");
let parentRow = document.getElementsByTagName('tr')
let clone = parentRow[1].cloneNode(true);
parentTable.appendChild(clone)
}

Related

Increment the id of html field [duplicate]

I have this table with some dependents information and there is a add and delete button for each row to add/delete additional dependents. When I click "add" button, a new row gets added to the table, but when I click the "delete" button, it deletes the header row first and then on subsequent clicking, it deletes the corresponding row.
Here is what I have:
Javascript code
function deleteRow(row){
var d = row.parentNode.parentNode.rowIndex;
document.getElementById('dsTable').deleteRow(d);
}
HTML code
<table id = 'dsTable' >
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(this)" </td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(this)" </td>
</tr>
</table>
JavaScript with a few modifications:
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
And the HTML with a little difference:
<table id="dsTable">
<tbody>
<tr>
<td>Relationship Type</td>
<td>Date of Birth</td>
<td>Gender</td>
</tr>
<tr>
<td>Spouse</td>
<td>1980-22-03</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
<tr>
<td>Child</td>
<td>2008-23-06</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
</tbody>
</table>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
jQuery has a nice function for removing elements from the DOM.
The closest() function is cool because it will "get the first element that matches the selector by testing the element itself and traversing up through its ancestors."
$(this).closest("tr").remove();
Each delete button could run that very succinct code with a function call.
Lots of good answers, but here is one more ;)
You can add handler for the click to the table
<table id = 'dsTable' onclick="tableclick(event)">
And then just find out what the target of the event was
function tableclick(e) {
if(!e)
e = window.event;
if(e.target.value == "Delete")
deleteRow( e.target.parentNode.parentNode.rowIndex );
}
Then you don't have to add event handlers for each row and your html looks neater. If you don't want any javascript in your html you can even add the handler when page loads:
document.getElementById('dsTable').addEventListener('click',tableclick,false);
​​
Here is working code: http://jsfiddle.net/hX4f4/2/
I would try formatting your table correctly first off like so:
I cannot help but thinking that formatting the table could at the very least not do any harm.
<table>
<thead>
<th>Header1</th>
......
</thead>
<tbody>
<tr><td>Content1</td>....</tr>
......
</tbody>
</table>
Here's the code JS Bin using jQuery. Tested on all the browsers. Here, we have to click the rows in order to delete it with beautiful effect. Hope it helps.
I suggest using jQuery. What you are doing right now is easy to achieve without jQuery, but as you will want new features and more functionality, jQuery will save you a lot of time. I would also like to mention that you shouldn't have multiple DOM elements with the same ID in one document. In such case use class attribute.
html:
<table id="dsTable">
<tr>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
<tr>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" class="addDep" value="Add"/></td>
<td> <input type="button" class="deleteDep" value="Delete"/></td>
</tr>
</table>
javascript:
$('body').on('click', 'input.deleteDep', function() {
$(this).parents('tr').remove();
});
Remember that you need to reference jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Here a working jsfiddle example:
http://jsfiddle.net/p9dey/1/
Use the following code to delete the particular row of table
<td>
<asp:ImageButton ID="imgDeleteAction" runat="server" ImageUrl="~/Images/trash.png" OnClientClick="DeleteRow(this);return false;"/>
</td>
function DeleteRow(element) {
document.getElementById("tableID").deleteRow(element.parentNode.parentNode.rowIndex);
}
try this for insert
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
and this for delete
document.getElementById("myTable").deleteRow(0);
Yeah It is working great
but i have to delete from localstorage too, when user click button , here is my code
function RemoveRow(id) {
// event.target will be the input element.
// console.log(id)
let td1 = event.target.parentNode;
let tr1 = td1.parentNode;
tr1.parentNode.removeChild(tr1);// the row to be removed
// const books = JSON.parse(localStorage.getItem("books"));
// const newBooks= books.filter(book=> book.id !== books.id);
// console.log(books, newBooks)
// localStorage.setItem("books", JSON.stringify(newBooks));
}
// function RemoveRow(btn) {
// var row = btn.parentNode.parentNode;
// row.parentNode.removeChild(row);
// }
button tag
class Display {
add(book) {
console.log('Adding to UI');
let tableBody = document.getElementById('tableBody')
let uiString = `<tr class="tableBody" id="tableBody" data-id="${book.id}">
<td id="search">${book.name}</td>
<td>${book.author}</td>
<td>${book.type}</td>
<td><input type="button" value="Delete Row" class="btn btn-outline-danger" onclick="RemoveRow(this)"></td>
</tr>`;
tableBody.innerHTML += uiString;
// save the data to the browser's local storage -----
const books = JSON.parse(localStorage.getItem("books"));
// console.log(books);
if (!books.some((oldBook) => oldBook.id === book.id)) books.push(book);
localStorage.setItem("books", JSON.stringify(books));
}
Hi I would do something like this:
var id = 4; // inital number of rows plus one
function addRow(){
// add a new tr with id
// increment id;
}
function deleteRow(id){
$("#" + id).remove();
}
and i would have a table like this:
<table id = 'dsTable' >
<tr id=1>
<td> Relationship Type </td>
<td> Date of Birth </td>
<td> Gender </td>
</tr>
<tr id=2>
<td> Spouse </td>
<td> 1980-22-03 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)" </td>
</tr>
<tr id=3>
<td> Child </td>
<td> 2008-23-06 </td>
<td> female </td>
<td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
<td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)" </td>
</tr>
</table>
Also if you want you can make a loop to build up the table. So it will be easy to build the table. The same you can do with edit:)

How to add dynamic rows with dynamic id in table using jquery

I have a different rows with different columns . I want to add those dynamically.
As my code is
$('.add-invoice-item').click(function (e) {
e.preventDefault();
row += 1;
var elem = $(".temp-tr tr").clone();
elem.find('.alt_date').attr('id', 'invi_date' + row);
$('.invoice-items').append(elem);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tbody class="invoice-items">
</tbody>
<div class="temp-tr hidden-element">
<table>
<tr>
<input type="text" name = "text1"/>
</tr>
<tr>
<input type="text" name = "text2"/>
</tr>
</table>

Delete tabel row with pure javascript

I Need to delete a table row with pure javascript. The table has only a class name, no id.
Here is a fiddle with my first try:
var table = document.getElementsByClassName('table');
while(table.rows.length > 0) {
table.deleteRow(1);
}
https://jsfiddle.net/5s0w6cwL/
Thanks for any advice.
You have to get first element.
var table = document.getElementsByClassName('table')[0];
because document.getElementsByClassName method returns a NodeList.
var table = document.getElementsByClassName('table')[0];
table.deleteRow(1);
<table class="table" border="1">
<tbody>
<tr>
<td> </td>
</tr>
<tr>
<td>delete me</td>
</tr>
<tr>
<td> </td>
</tr>
</tbody>
</table>

incrementing the value of a input field in the cloned row

1)here i'm doing clone of a row...but this code is working only in eclipse [ ie ,cloning is working ] and it is also not working in any browsers.
2)What is the solution to get the values of text boxes in the cloned rows having same name, and insert into the database using jsp and servlet?
how can i get those values with same name
3)i have servlet code to get only single value from jsp
String address_seq_num =request.getParameter("address_seq_num");
how can i get the value of address seq number in the cloned row fromjsp to servlet to insert into the next row of a table in the database.
4)if i mention "DOCUMENT TYPE" to this code ,it will not work in eclipse also.....
please guide me...
JavaScript
function clonetable() {
var x=document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
var row = document.getElementById("table_row_clone"); // find row to copy
var table = document.getElementById("table_body"); // find table to append to
var clone = row.cloneNode(true); // copy children too
var tb1 = clone.document.getElementById("asn");//here i'm incrementing the value
tb1.value=rowCount+1;//of "address seq num " in the cloned row
clone.id = "abc"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
function deltable() {
var x = document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
if (rowCount > 1) {
x.deleteRow(rowCount - 1);
} //delete the last row
}
HTML
<table id="main_table" align="center" style="width:75%">
<tbody id="table_body">
<tr id="table_row_clone">
<td>
<table align="center" style="width:100%">
<tr>
<td align="center">
<div style="border:3px solid silver;border-radius:5px;background-color:grey">
<table width="100%">
<tr>
<th align="center">Address Details</th>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div style="border:3px solid silver;border-radius:5px;background-color:#1E90FF">
<table align="center" style="width:99%">
<tr style="background-color:#1E90FF">
<td style="width:35%">
<table width="100%">
<tr id="slrow">
<td style="width:43%">Address Seq Num</td>
<td>
<input id="asn" style="width:60px" name="address_seq_num" type="text" value="1" readonly>
</td>
</tr>
</table>
</td>
<td width="49%" align="right">
<input style="width:80%" type="text" value="Reg.office/Primary Office">
</td>
<td align="right">
<input style="width:30px" type="button" value="+" onclick="clonetable()">
<input style="width:30px" type="button" value="-" onclick="deltable()">
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</td>
</tr>
</tbody>
Per your HTML (which is messy, by the way) you can increment that textbox's value with something like:
var tb = document.getElementById("asn");
tb.value = parseInt(tb.value, 10) + 1;
The trick is you have to cast the textbox's value into a number, which is what parseInt is doing in that example.
Note that the above snippet will give you "NaN" in the textbox if the value is not a valid number - it's not doing any data validation at all.

Change the value of a text box to its current order in a sortable tab

Edit: I have solved this by myself. See my answer below
I have set up a nice sortable table with jQuery and it is quite nice. But now i want to extend it.
Each table row has a text box, and i want i am after is to, every time a row is dropped, the text boxes update to reflect the order of the text boxes. E.g. The text box up the top always has the value of '1', the second is always '2' and so on.
I am using jQuery and the Table Drag and Drop JQuery plugin
Code
Javascript:
<script type = "text/javascript" >
$(document).ready(function () {
$("#table-2").tableDnD({
onDrop: function (table, row) {
var rows = table.tBodies[0].rows;
var debugStr = "Order: ";
for (var i = 0; i < rows.length; i++) {
debugStr += rows[i].id + ", ";
}
console.log(debugStr)
document.forms['productform'].sort1.value = debugStr;
document.forms['productform'].sort2.value = debugStr;
document.forms['productform'].sort3.value = debugStr;
document.forms['productform'].sort4.value = debugStr;
},
});
});
</script>
HTML Table:
<form name="productform">
<table cellspacing="0" id="table-2" name="productform">
<thead>
<tr>
<td>Product</td>
<td>Order</td>
</tr>
</thead>
<tbody>
<tr class="row1" id="Pol">
<td>Pol</td>
<td><input type="textbox" name="sort1"/></td>
</tr>
<tr class="row2" id="Evo">
<td>Evo</td>
<td><input type="textbox" name="sort2"/></td>
</tr>
<tr class="row3" id="Kal">
<td>Kal</td>
<td><input type="textbox" name="sort3"/></td>
</tr>
<tr class="row4" id="Lok">
<td>Lok</td>
<td><input type="textbox" name="sort4"/></td>
</tr>
</tbody>
</table>
</form>
Hardnrg in #jquery ended up solving it for me.
It involved adding an id="" to each input:
<form name="productform">
<table cellspacing="0" id="table-2" name="productform">
<thead>
<tr><td>Product</td> <td>Order</td></tr>
</thead>
<tbody>
<tr class="row1" id="Pol"> <td>Pol</td> <td><input id="Pol_field" type="textbox" name="sort1"/></td> </tr>
<tr class="row2" id="Evo"> <td>Evo</td> <td><input id="Evo_field" type="textbox" name="sort2"/></td> </tr>
<tr class="row3" id="Kal"> <td>Kal</td> <td><input id="Kal_field" type="textbox" name="sort3"/></td> </tr>
<tr class="row4" id="Lok"> <td>Lok</td> <td><input id="Lok_field" type="textbox" name="sort4"/></td> </tr>
</tbody>
</table>
</form>
And add this js to the OnDrop event:
for (var i=0; i < rows.length; i++) {
$('#' + rows[i].id + "_field").val(i+1);
}
Easy peasy!
Hmmm..
I think you want to do something like this:
$("input:text", "#table-2").each( function(i){ this.value=i+1; });
The $().each() function's info is here: http://docs.jquery.com/Core/each

Categories