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

I want to duplicate the second <tr> everytime I click button add, as it shows in here, I mean I want to whenever I click on the button add a new <tr> will be added that do the same thing as the previous one.
<form id="frm1" action="Calculate.html">
<table id= "myTable">
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
</tr>
<tr id= "rowToClone">
<td>
<select id= "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" id="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="Calculate()" value="calculate">
<input type="button" onclick="AddSelect()" value="Add">
I want it to do the same whole thing, I tried but never got successful the second part I am stuck to
first part:
function Calculate() {
var e = document.getElementById("products");
var productValue = e.options[e.selectedIndex].value;
document.getElementById("ndpc").innerHTML = productValue;
document.getElementById("ndpc").value = productValue;
if (e.selectedIndex === 0){
document.getElementById("pu").value = 21.2;
}
else if (e.selectedIndex === 1) {
document.getElementById("pu").value = 25.7;
}
else if (e.selectedIndex === 2 || e.selectedIndex === 3 ) {
document.getElementById("pu").value = 14;
}
else {
document.getElementById("pu").value = 6;
}
var pu = document.getElementById("pu").value;
document.getElementById("pu").innerHTML = pu;
var ndc = document.getElementById("ndc").value;
var ndpc = document.getElementById("ndpc").value;
var Result = ndc * ndpc * pu;
document.getElementById("ptpp").innerHTML = Result;
};
the second part that I want to solve:
function AddSelect(){
var row = document.getElementbyId("rowToClone");
var table = document.getElementById("myTable");
var clone = row.cloneNode(true);
clone.id = "New";
function createRow() {
//I don't know what to do.
} };
I am new to Javascript obviously, please help me.

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>

Related

Remove values from input fields when creating a new table row

I'm trying to create a new role but I want a row where there isn't any value in the textfield.
<form action="Fruits" method="Post" enctype="multipart/form-data">
<table id="myTable">
<c:forEach items="${fruits}" var="val" varStatus="count">
<thead>
<tr>
<th>Fruit</th>
<th>Color</th>
</thead>
<tbody>
<td><input type="text" name="name" id="name" value="${val.name}"></td>
<td><input type="text" name="color" id="color" value="${val.color}"></td>
</tbody>
</table>
<button type="button" class="btn btn-default json-editor-btn-add" onclick="myFunction()">Add</button>
</form>
For now whenever I create a new role, it gives me the values of the first row and fill the text field. Is there a way where I just create a row where it doesnt have any values.
function myFunction(){
var table = document.getElementById("myTable");
var first_tr = table.firstElementChild;
var second_tr = first_tr.nextElementSibling;
var tr_clone = first_tr.cloneNode(true);
var tb_clone = second_tr.cloneNode(true);
table.append(tr_clone);
table.append(tb_clone);
}
I'm expecting a blank field text for all of the column upon creating a row
Instead of cloning previous rows create a row template using a template/string literal that you can insert before the end of the tbody element.
Note: you don't have any rows in your current table's - you just have two cells. You also can't have multiple cells with the same id. Ids are supposed to be unique within a document. If you have to identify cells separately you should use a data attribute instead.
const rowTmpl = `<tr>
<td><input type="text" name="name"></td>
<td><input type="text" name="color"></td>
</tr>`;
const tbody = document.querySelector('tbody');
const button = document.querySelector('button');
button.addEventListener('click', handleClick);
function handleClick(e) {
tbody.insertAdjacentHTML('beforeend', rowTmpl);
}
<table>
<thead>
<tr><td>Fruit</td><td>Color</td></tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" value="Apple" name="name"></td>
<td>
<input type="text" value="Red" name="color">
</td>
</tr>
</tbody>
</table>
<button type="button">Add row</button>
Add below lines in your function.
let array_of_input = tb_clone.querySelectorAll('input');
array_of_input.forEach(cur => {
cur.value = '';
})
Your final function looks like this.
function myFunction() {
var table = document.getElementById("myTable");
var first_tr = table.firstElementChild;
var second_tr = first_tr.nextElementSibling;
var tr_clone = first_tr.cloneNode(true);
var tb_clone = second_tr.cloneNode(true);
table.append(tr_clone);
table.append(tb_clone);
let array_of_input = tb_clone.querySelectorAll('input');
array_of_input.forEach(cur => {
cur.value = '';
})
}

Clone table and display after button

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)
}

Getting next element in a table javascript

https://jsfiddle.net/en6jh7pa/1/
I am having issues grabbing the next element, it is returning null for the next element.
I am passing "this? as onclick and I assumed that you could use this to grab the next element but it seems that it instead returns null
Thanks for your help
function assignnames(checkboxelement){
checkboxelement.setAttribute("name", "checkbox");
var value1box = checkboxelement.nextSibling;
value1box.setAttribute("name", "notnull");
var value2box = checkboxelement.nextElementSibling;
value2box.setAttribute("name", "notnull");
alert("done");
}
<table border="1">
<tr>
<th>
Checkbox
</th>
<th>
value1
</th>
<th>
value2
</th>
</tr>
<tr>
<td>
<input type="checkbox" onclick="assignnames(this)" id="checkbox1"/>
</td>
<td>
<input type="text" name="" id="fname1">
</td>
<td>
<input type="text" name="" id="lname1">
</td>
</tr>
</table>
If you want to get the text inputs in the same row, you can go up to the row, then use a selector to get the inputs, e.g.
function getParent(node, tag) {
var tag = tag.toLowerCase();
do {
if (node.tagName.toLowerCase() == tag) {
return node;
}
node = node.parentNode;
} while (node && node.tagName && node.parentNode)
return null;
}
function getInputs(evt) {
var row = getParent(this, 'tr');
var inputs;
if (row) {
inputs = row.querySelectorAll('input[type="text"]');
}
console.log(`Found ${inputs.length} text inputs, node is ${this.checked? '':'not '}checked.`);
}
window.onload = function(){
document.getElementById('checkbox1').addEventListener('click', getInputs, false);
};
<table border="1">
<tr><th>Checkbox
<th>value1
<th>value2
<tr><td><input type="checkbox" id="checkbox1">
<td><input type="text" name="" id="fname1">
<td><input type="text" name="" id="lname1">
</table>
For the inputs to be siblings, they would all have to be within the same <td>, sharing a singular parent. With them spread out across multiple table cells, they would be considered cousins instead (keeping with the family tree metaphor), which doesn't have a similar shortcut property.
You can still use nextElementSibling along the way between inputs, but you'll also have to move up and back down between generations.
function assignnames(checkboxelement){
checkboxelement.setAttribute("name", "checkbox");
var value1box = checkboxelement
.parentElement // up a generation the checkbox' parent <td>
.nextElementSibling // then to the next <td> in the row
.firstElementChild; // and back down a generation to the next input
// the last step could also be: .querySelector('input')
value1box.setAttribute("name", "notnull");
var value2box = value1box
.parentElement
.nextElementSibling
.firstElementChild;
value2box.setAttribute("name", "notnull");
alert("done");
}
<table border="1">
<tr>
<th>
Checkbox
</th>
<th>
value1
</th>
<th>
value2
</th>
</tr>
<tr>
<td>
<input type="checkbox" onclick="assignnames(this)" id="checkbox1"/>
</td>
<td>
<input type="text" name="" id="fname1">
</td>
<td>
<input type="text" name="" id="lname1">
</td>
</tr>
</table>

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:)

getting and using textbox text and changing its color by html select box

function Start(){
var headerr = document.getElementById("pageh").value;
var hcolor = document.getElementById("hcolor").value;
var hsize = document.getElementById("hsize").value;
document.body.innerHTML = "";
}
That's the JS code for taking the value of the textbox and the select boxes.
<tr>
<td>page header</td>
<td>
<input type="text" id="pageh" /></td>
</tr>
<tr>
<td>Header color:</td>
<td>
<select id="hcolor">
<option>red</option>
<option>purple</option>
<option>gray</option>
</select></td>
</tr>
<tr>
<td>Header size</td>
<td>
<select id="hsize">
<option>small</option>
<option>normal</option>
<option>big</option>
</select></td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Send" onclick="Start()" /><input type="reset" value="Clear" /></td>
</tr>
And the HTML code for the textbox and the select boxes.
So what can I do for posting the text and manipulating its color and size?
I thought about using document.write(""headerr""); but it doesn't seem to work.
ETA JSFiddle: http://jsfiddle.net/7LNMn/
Thank you!!
function Start(){
var headerr = document.getElementById("pageh").value;
var hcolor = document.getElementById("hcolor").value;
var hsize = document.getElementById("hsize").value;
var g = document.getElementById("header"); // var g will store document.getElementById("header") so, i don't have to write much whereas header can be changed by the element's id e.g. header of website!
g.style.background = hcolor; // here g will get the element and style its bg
g.style.fontSize = hsize; // here its fontSize
// and I dont know what to do with pageh variable!
}

Categories