How to create a dynamic table in JavaScript

A dynamic table is characterized by its ability to change the number of rows according to the input it processes during execution. Various online platforms or web applications, including corporate websites, necessitate the real-time generation of tables when incorporating data or information. This functionality is achievable due to JavaScript, a programming language known for its dynamic typing capabilities.

In order to generate a dynamic table using JavaScript, you can adhere to the following guidelines:

  1. Begin by establishing an HTML element that will serve as the container for the table. For instance, you can create a div element and assign it an id attribute, which will allow you to reference it later within your JavaScript code:
  2. Example
    
    <div id="table-container"></div>
    
  3. In your JavaScript code, create an array containing the data you wish to present in the table. For instance:
  4. Example
    
    const data = [
    
    { name: 'John', age: 30, email: 'john@example.com' },
    
    { name: 'Jane', age: 25, email: 'jane@example.com' },
    
    { name: 'Bob', age: 40, email: 'bob@example.com' }
    
    ];
    
  5. Develop a function that constructs the HTML markup for a table using the provided data array. For instance:
  6. Example
    
    function generateTable(data) {
    
    let table = '<table>';
    
    table += '<tr><th>Name</th><th>Age</th><th>Email</th></tr>';
    
    data.forEach(item => {
    
    table += `<tr><td>${item.name}</td><td>${item.age}</td><td>${item.email}</td></tr>`;
    
    });
    
    table += '</table>';
    
    return table;
    
    }
    
  7. Invoke the generateTable function by passing in the data array, and then attach the generated HTML markup to the table container element. For instance:
  8. Example
    
    const tableContainer = document.getElementById('table-container');  
    
    tableContainer.innerHTML = generateTable(data);
    
  9. You may also enhance the appearance of the table by applying CSS styles, which can contribute to a more attractive design. For instance:
  10. Example
    
    table {
    
    border-collapse: collapse;
    
    width: 100%;
    
    }
    
    
    
    th, td {
    
    border: 1px solid #ddd;
    
    padding: 8px;
    
    text-align: left;
    
    }
    
    
    
    th {
    
    background-color: #4CAF50;
    
    color: white;
    
    }
    

Congratulations! You have successfully created a dynamic table that can be modified with new information whenever required.

Example:

Below is an additional illustration that creates a dynamic table based on input provided by the user.

Example

<!DOCTYPE html>

<html>

<head>

<title>Dynamic Table Example</title>

<style>

table {

border-collapse: collapse;

width: 100%;

}



th, td {

border: 1px solid #ddd;

padding: 8px;

text-align: left;

}



th {

background-color: #4CAF50;

color: white;

}

</style>

</head>

<body>

<div>

<label for="rows">Number of Rows:</label>

<input type="number" id="rows" name="rows" value="3">

<label for="cols">Number of Columns:</label>

<input type="number" id="cols" name="cols" value="3">

<button onclick="generateTable()">Generate Table</button>

</div>

<div id="table-container"></div>



<script>

function generateTable() {

const rows = document.getElementById('rows').value;

const cols = document.getElementById('cols').value;

let table = '<table>';

for (let i = 0; i< rows; i++) {

table += '<tr>';

for (let j = 0; j < cols; j++) {

table += `<td>Row ${i + 1}, Column ${j + 1}</td>`;

}

table += '</tr>';

}

table += '</table>';

const tableContainer = document.getElementById('table-container');  

tableContainer.innerHTML = table;  

}

</script>

</body>

</html>

Output

Explanation:

This script creates an input form that allows users to define the desired quantity of rows and columns for a table. Upon clicking the "Generate Table" button, the generateTable function is triggered. This function gathers the values input by the user, constructs an HTML table with the indicated number of rows and columns, and subsequently places the table within the table-container element.

Note that:- This example does not use an array of data like the previous example, but instead generates the table content dynamically using loops . You can modify the loop logic to generate different table content as needed.

Example:

Below is an additional example that creates a dynamic table by utilizing information obtained from an external API.

Example

<!DOCTYPE html>

<html>

<head>

<title>Dynamic Table Example</title>

<style>

table {

border-collapse: collapse;

width: 100%;

}



th, td {

border: 1px solid #ddd;

padding: 8px;

text-align: left;

}



th {

background-color: #4CAF50;

color: white;

}

</style>

</head>

<body>

<div id="table-container"></div>



<script>

async function generateTable() {

try {

const response = await fetch('https://jsonplaceholder.typicode.com/users');

const data = await response.json();

let table = '<table>';

table += '<tr><th>Name</th><th>Email</th><th>Phone</th></tr>';

data.forEach(item => {

table += `<tr><td>${item.name}</td><td>${item.email}</td><td>${item.phone}</td></tr>`;

});

table += '</table>';

const tableContainer = document.getElementById('table-container');  

tableContainer.innerHTML = table;  

} catch (error) {

console.error(error);

}

}



generateTable();

</script>

</body>

</html>

Output

Name Email Phone
Leanne Graham [email protected] 1-770-736-8031 x56442
Ervin Howell [email protected] 010-692-6593 x09125
Clementine Bauch [email protected] 1-463-123-4447
Patricia Lebsack [email protected] 493-170-9623 x156
Chelsey Dietrich [email protected] (254)954-1289
Mrs. Dennis Schulist [email protected] 1-477-935-8478 x6430
Kurtis Weissnat [email protected] 210.067.6132
Nicholas Runolfsdottir V [email protected] 586.493.6943 x140
Glenna Reichert [email protected] (775)976-6794 x41206
Clementina DuBuque [email protected] 024-648-3804

Explanation:

This snippet employs the fetch function to obtain information from an external API (https://jsonplaceholder.typicode.com/users). The API provides an array of user objects, which are then utilized to create an HTML table featuring three columns: Name, Email, and Phone. The async/await syntax is implemented to manage the asynchronous behavior of the fetch function.

Note that:- In this example, the generateTable function is called automatically when the page loads, so the table is generated without the need for user input. You can modify the API endpoint to retrieve different data, and the table columns and content will update accordingly.

Input Required

This code uses input(). Please provide values below: