Learn how to create a dynamic HTML table using HTML, CSS, and JavaScript. This step-by-step tutorial guides you through building an interactive table with features like adding, deleting, and editing rows.
Table of Contents
HTML tables have long been a fundamental element in web development, providing a way to present data in a structured and organized manner. However, static tables can sometimes fall short when it comes to interactivity and dynamic content. That's where a dynamic HTML table comes into play.
A dynamic HTML table allows users to interact with the table in real time, adding, deleting, and editing rows as needed. This level of interactivity enhances the user experience and provides greater flexibility when working with data. Whether you're building a data management system, an e-commerce platform, or a collaborative spreadsheet-like application, a dynamic table can significantly improve the usability and functionality of your web project.
In this tutorial, we will explore the process of creating a dynamic HTML table using a combination of HTML, CSS, and JavaScript. We will guide you through each step, providing detailed explanations and code examples along the way. By the end of this tutorial, you will have the knowledge and skills to implement your own dynamic tables and take your web projects to the next level.
Before we dive into the technical details, it's important to understand the separation of concerns between HTML, CSS, and JavaScript in web development. HTML (Hypertext Markup Language) provides the structure and content of the web page, CSS (Cascading Style Sheets) is responsible for the visual presentation and styling, and JavaScript adds interactivity and dynamic behavior to the page.
Let's start making an amazing dynamic table using HTML, CSS, and JavaScript step by step.
Join My Telegram Channel to Download the Projects Source Code: Click Here
Prerequisites:
Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.
Source Code
Step 1 (HTML Code):
To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our table.
After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.
Let's break down the code section by section:
1. <!DOCTYPE html>: This line declares the document type as HTML5, which is the latest version of HTML.
2. <html>: This tag represents the root element of an HTML document and contains all other elements.
3. <head>: This section contains meta-information about the HTML document, such as the title, stylesheets, and scripts.
4. <title>Dynamic HTML Table with JavaScript</title>: This line sets the title of the webpage, which will be displayed in the browser's title bar or tab.
5. <link rel="stylesheet" href="styles.css">: This line includes an external stylesheet file named "styles.css," which is used to define the visual styles (e.g., colors, fonts, layout) for the webpage.
6. </head>: This closing tag indicates the end of the <head> section.
7. <body>: This section contains the visible content of the webpage that will be displayed in the browser's viewport.
8. <div class="container">: This <div> element serves as a container to hold the content of the webpage.
9. <h1>Dynamic Table</h1>: This line creates a heading level 1 (<h1>) element that displays the text "Dynamic Table."
10. <div class="input-container">: This <div> element acts as a container for input elements.
11. <input type="number" id="columns" min="1" placeholder="Number of Columns">: This line creates an input field of type "number" with an id attribute set to "columns." It allows users to input a numeric value and specifies a minimum value of 1. The placeholder attribute displays the text "Number of Columns" as a hint inside the input field.
12. <input type="number" id="rows" min="1" placeholder="Number of Rows">: Similar to the previous line, this input field allows users to input the number of rows for the table.
13. <button onclick="createTable()">Create Table</button>: This line creates a button element with the text "Create Table." The onclick attribute specifies that when the button is clicked, it should execute the JavaScript function createTable().
14. </div>: This closing tag indicates the end of the <div> element with the class "input-container."
15. <table id="myTable">: This line creates a table element with an id attribute set to "myTable." The table will be used to display the dynamically generated content.
16. <!-- Table will be dynamically generated here -->: This is an HTML comment that indicates where the table's content will be dynamically generated using JavaScript.
17. </table>: This closing tag indicates the end of the <table> element.
18. </div>: This closing tag indicates the end of the <div> element with the class "container."
19. <script src="script.js"></script>: This line includes an external JavaScript file named "script.js" that contains the code for dynamically generating the table and handling user interactions.
20. </body>: This closing tag indicates the end of the <body> section.
21. </html>: This closing tag indicates the end of the HTML document.
This is the basic structure of our table using HTML, and now we can move on to styling it using CSS.
Step 2 (CSS Code):
Once the basic HTML structure of the table is in place, the next step is to add styling to the table using CSS.
Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our table.
Here's a breakdown of the different styles defined in the code:
1. The .container class sets the width to 60% and centers it horizontally using margin: 0 auto;.
2. The h1 selector sets the top margin to 0 and aligns the text in the center.
3. The .input-container class sets the display to flex, justifies the content to the center, and allows wrapping of flex items.
4. The #rows and #columns IDs define styles for input elements with those IDs. They have padding, font size, margin-right, border radius, and border styles. When focused, they change the border color and apply a box shadow.
5. The button selector defines styles for a button element. It sets the padding, font size, cursor, background color, text color, border, and border radius. On hover, the background color changes.
6. The table selector sets the border-collapse property to collapse and the width to 100%.
7. The .header-input class sets the width to 100%, removes the border and outline, and applies bold font weight and uppercase text transformation.
8. The #myTable ID sets a top margin of 30px.
9. The th and td selectors set the border and padding for table header and data cells, and align the text to the left.
10. The .editable-cell class sets the background color to #f2f2f2 and removes the outline. It is likely used for editable cells in the table.
11. The input styles at the bottom of the code are browser-specific and handle the appearance of number input fields in different browsers.
This will give our dynamic table an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.
.container{
width: 60%;
margin: 0 auto;
}
h1 {
margin-top: 0;
text-align: center;
}
.input-container{
display: flex;
justify-content: center;
flex-wrap: wrap;
}
#rows,
#columns {
padding: 10px;
font-size: 16px;
margin-right: 10px;
border-radius: 5px;
border: 1px solid #ccc;
}
#rows:focus,
#columns:focus{
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102,175,233,.6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102,175,233,.6);
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
}
button:hover {
background-color: #3e8e41;
}
table {
border-collapse: collapse;
width: 100%;
}
.header-input {
width: 100%;
box-sizing: border-box;
font-weight: bold;
border: none;
outline: none;
text-transform: uppercase;
}
#myTable{
margin-top: 30px;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
.editable-cell {
background-color: #f2f2f2;
outline: none
}
/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Firefox */
input[type=number] {
-moz-appearance: textfield;
}
Step 3 (JavaScript Code):
Finally, we need to create a dynamic function for table in JavaScript.
Here's a breakdown of what each part of the code does:
1. The code begins by declaring an empty array called tableData to store the data from the table.
2. The createTable() function is responsible for creating the HTML table based on user input. It retrieves the necessary elements from the HTML document, such as the table itself (myTable), the input fields for columns and rows, and the corresponding values entered by the user.
3. The function then clears any existing content in the table by removing all child elements.
4. Next, it creates the table header by dynamically generating th (table header) elements based on the number of columns specified. Each th element contains an input field with a class and placeholder text.
5. After creating the table header, the function proceeds to create the table rows. It iterates over the specified number of rows and columns, creating td (table cell) elements for each cell. These cells have the attribute contenteditable set to "true", allowing the user to edit the cell content. An event listener is attached to each cell, which triggers the updateCell() function whenever the content of a cell is modified. The cell data is stored in the tableData array.
6. The updateCell() function is called when the content of a cell changes. It extracts the row and column indices of the modified cell and retrieves the updated value. It then calls the updateData() function to update the corresponding value in the tableData array.
7. The updateData() function updates the value at the specified row and column indices in the tableData array.
8. The deleteRow() function is responsible for deleting a specified row from the table. It removes the row from the HTML table and also removes the corresponding row data from the tableData array.
9. The updateRow() function updates the data of a specified row in the tableData array based on the current content of the cells in the HTML table. It retrieves the table, the data of the specified row from tableData, and the cells of the row. It then iterates over the cells, retrieves the updated values, and stores them in the rowData array.
10. The displayData() function logs the tableData array to the console, displaying the current data stored in the table.
Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.
var tableData = [];
function createTable() {
var table = document.getElementById("myTable");
var columnsInput = document.getElementById("columns");
var rowsInput = document.getElementById("rows");
var columns = parseInt(columnsInput.value);
var rows = parseInt(rowsInput.value);
// Clear existing table
while (table.firstChild) {
table.removeChild(table.firstChild);
}
// Create table header
var headerRow = document.createElement("tr");
for (var i = 0; i < columns; i++) {
var th = document.createElement("th");
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("class", "header-input");
input.setAttribute("placeholder", "Column " + (i + 1));
th.appendChild(input);
headerRow.appendChild(th);
}
table.appendChild(headerRow);
// Create table rows
for (var i = 0; i < rows; i++) {
var rowData = [];
var row = document.createElement("tr");
for (var j = 0; j < columns; j++) {
var cell = document.createElement("td");
cell.setAttribute("contenteditable", "true");
cell.setAttribute("class", "editable-cell");
cell.addEventListener("input", updateCell);
rowData.push("");
row.appendChild(cell);
}
table.appendChild(row);
tableData.push(rowData);
}
}
function updateCell(event) {
var rowIndex = event.target.parentNode.rowIndex - 1;
var columnIndex = event.target.cellIndex;
var value = event.target.textContent.trim();
updateData(rowIndex, columnIndex, value);
}
function updateData(row, col, value) {
tableData[row][col] = value;
}
function deleteRow(row) {
var table = document.getElementById("myTable");
table.deleteRow(row);
tableData.splice(row, 1);
}
function updateRow(row) {
var table = document.getElementById("myTable");
var rowData = tableData[row];
var cells = table.rows[row + 1].cells;
for (var i = 0; i < rowData.length; i++) {
var value = cells[i].textContent.trim();
rowData[i] = value;
}
}
function displayData() {
console.log(tableData);
}
Final Output:
See the Pen Untitled by Faraz (@codewithfaraz) on CodePen.
Conclusion:
In this tutorial, we have explored the process of creating a dynamic HTML table using HTML, CSS, and JavaScript. We started by setting up the HTML structure of the table, creating the necessary elements for the table header and data rows. Then, we proceeded to style the table using CSS to enhance its visual presentation.
The real power of our dynamic table came from implementing JavaScript functionality. We learned how to add rows dynamically, allowing users to insert new data into the table on the fly. Additionally, we explored how to delete rows dynamically, giving users the ability to remove unwanted data rows. Finally, we delved into editing rows dynamically, enabling users to modify existing data in the table.
By following the step-by-step instructions and understanding the underlying concepts, you now have the knowledge and skills to create your own dynamic HTML tables. You can apply this knowledge to various web development projects where interactive and flexible tables are required.
Remember, a clean and semantic HTML structure is crucial for accessibility and maintainability. Styling the table with CSS provides the desired visual representation, while JavaScript adds interactivity and dynamic behavior. Don't be afraid to experiment and customize the table to suit your specific needs and design requirements.
As you continue to advance in your web development journey, keep exploring additional features and functionalities you can incorporate into your dynamic tables. You may consider sorting, filtering, or pagination options to further enhance the user experience. The possibilities are endless!
We hope this tutorial has provided you with a solid foundation for creating dynamic HTML tables. Feel free to refer back to this guide whenever you need a refresher or when you're ready to embark on your next web project.
That’s a wrap!
I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.
Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee
And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!
Thanks!
Faraz 😊