June 4, 2020
How to Add Row to HTML Table Using Javascript
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <div id="data"> <input type="text" id="name" placeholder="Enter Name"> <input type="number" id="age" placeholder="Enter Age"> <input type="text" id="country" placeholder="Enter Country"> <button>Add</button> </div> <table> <tr> <th>Name</th> <th>Age</th> <th>Country</th> </tr> <tr> <td>Peter</td> <td>20</td> <td>USA</td> </tr> <tr> <td>James</td> <td>40</td> <td>UK</td> </tr> <tr> <td>Ronald</td> <td>30</td> <td>Canada</td> </tr> </table> </div> <script src="script.js"></script> </body> </html> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
.container { display: flex; flex-direction: column; align-items: center; } th,td { border: 1px solid black; padding: 10px; } #data { margin-bottom: 10px; } #data input, button { padding: 10px; width: 90px; } |
Javascript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
let btnAdd = document.querySelector('button'); let table = document.querySelector('table'); let nameInput = document.querySelector('#name'); let ageInput = document.querySelector('#age'); let countryInput = document.querySelector('#country'); btnAdd.addEventListener('click', () => { let name = nameInput.value; let age = ageInput.value; let country = countryInput.value; let template = ` <tr> <td>${name}</td> <td>${age}</td> <td>${country}</td> </tr>`; table.innerHTML += template; }); |