0

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?

2
  • 4
    Use document.createElement('input') instead of document.createTextNode() Commented Apr 20, 2022 at 18:07
  • You should not append multiple children in a loop to the document, it will slow down the performance of your app. Better use a DocumentFragment developer.mozilla.org/en-US/docs/Web/API/DocumentFragment and append it to the body after looping :) Commented Apr 20, 2022 at 18:26

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.