I want to create a dynamic table using html and javascript where the user enters number of rows, and want all table cells to be of input type
function createTable() {
var a, b, tableElem, rowElem, colElem;
a = 7
b = 5
if (a == "" || b == "") {
alert("Please enter some numeric value");
} else {
tableElem = document.createElement('table');
for (var i = 0; i < a; i++) {
rowElem = document.createElement('tr');
for (var j = 0; j < b; j++) {
colElem = document.createElement('td');
colElem.appendChild(document.createTextNode(j + 1)); //to print cell number
rowElem.appendChild(colElem);
}
tableElem.appendChild(rowElem);
}
document.body.appendChild(tableElem);
}
I found this code, but how to make all cells of input type?
Instead of adding input elements inside each table cell, an option would be setting the contenteditable attribute for each cell.
A simple event listener to detect focusout can trigger whatever steps you want to perform, such as extracting the entered text and setting it to variables for further computations.
This working snippet uses a table written in html but the same principle can be applied to the table added dynamically.
const cells = document.getElementsByTagName('td');
for (let i=0; i<cells.length; i++) {
cells[i].setAttribute("contenteditable", "");
cells[i].addEventListener('focusout', (event) => {
console.log(event.target.innerText);
});
} // next cell;
td {
width: 50px;
height: 1.2em;
border: 1px solid red;
}
table {
border-collapse: collapse;
}
<p>enter text in cells below:</p>
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>