Im new for Html and javascript. I want to create dynamic row with input fields in table while click button,that number of row given from user. In my code, row created dynami
Use
Element.appendChild
instead ofinnerHTML
Element.firstChild
will return first-child
of the element.querySelectorAll
will return NodeList
as per the specified selector.Element.appendChild
will append new Node
in the Element without affecting existing content in the Element. function createTable() {
var a = document.getElementById('tb1').value;
if (a == "") {
alert("Please enter some numeric value");
} else {
var th = document.querySelectorAll('#table th');//To check whether `TD` is appended in table or not!
if (!th.length) {
//If not appended, then append TD in table
var rows = "Item Name Quantity QuantityType Amount ";
var table = document.createElement('table');
table.innerHTML = rows;
document.getElementById("table").appendChild(table.firstChild);
}
for (var i = 0; i < a; i++) {
var elems = '';
elems += " ";
var table = document.createElement('table');
table.innerHTML = elems;
document.getElementById("table").appendChild(table.firstChild);
}
}
}
div {
background: red;
margin: 5px;
}
table {
border: 2px solid black;
}
td {
padding: 10px;
border: 1px solid lightgrey;
}