Editable HTML Table using JavaScript

Jeditable Html Table Using JavaScript
Project: Generate a dynamic table - javascript and HTML
Author: Khalid Munir
Edit Online: View on CodePen
License: MIT

This JavaScript code snippet helps you to generate an editable HTML table dynamically with rows and columns. Each cell in the table contains a text input element with a default value of the cell’s coordinates in the table (e.g. “01” for the first row, second column). If the column index is odd, the input element also has a data attribute set to the formula representing its coordinates. The table is inserted into the HTML document at the element with the ID “out”.

Moreover, the console log statement prints out the element with the ID “out” for debugging purposes.

How to Create Editable HTML Table using Javascript

First, create a table element with a unique id in which rows and columns rendered dynamically through JavaScript.

<table id="out">
</table>

After that, style the table using the following CSS styles. These CSS rules are optional, you can define your own according to your needs.

input{width:50px}
table {
  border:1px solid black;
  border-color:red;
}

Finally, add the following JavaScript function with your data to generate inside the HTML table.

document.body.onload = makeTable;

function  makeTable() {

var tab = document.getElementById("out");

console.log(tab);

for(var r=0;r<6;r++) {
  var dRow = tab.insertRow(-1);
  
  for(var c=0;c<10;c++) {
  // for each cell - generate a html element by using add child.
   var cell = dRow.insertCell(-1);
    
   var newInput = document.createElement("input");
   
   newInput.type = "text";
   newInput.className = "css-class-name"; // set the CSS class
    newInput.setAttribute("id",c);
    if(c % 2) { 
      newInput.setAttribute("data-formula", r.toString()+c);
      newInput.setAttribute("value", r.toString()+c);
    
    } else {
      newInput.setAttribute("value", r.toString()+c);

    }
    
    
  cell.appendChild(newInput); // put it into the DOM
    
    
   //cell.appendChild(); 
    
    
    
    
    
  }

}
  
}

That’s all! hopefully, you have successfully created an editable HTML table. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *