'how to create table using for loop by user input values in javascripts
I have form . I wish to display values in table by clicking on add button
note: values will be stored in arrays Use for loop
function loadTable() {
for (var i = 0; i < users.length; i++) {
"<tr id='row'>"
for (var j = 0; j < users[i].length; j++) {
$("#items_tbody").append(
"<td>" + items[i][j] +"</td>" +
)
+"</tr>"
console.log(items[i][j]);
}
}
}
table,
th,
td {
border: 1px solid black;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<!-- <form action="" method="get"> -->
<input type="number" name="id" id="id">
<input type="text" name="name" id="name">
<button type="button" id="submit">Add</button>
<table id="demo">
<tbody>
</tbody>
</table>
<!-- </form> -->
</body>
</html>
trying to get headers in tr and tbody data in tr seperatly but using for loop how can I do this
Solution 1:[1]
for (var j = 0; j < users[i].length; j++) {
$("#items_tbody").append(
"<td>" + items[i][j] +"</td>" +)
What this does is not create a DOM element. Just a string. Here's what you need to do:
- Create a element
const tdElement = document.createElement("td");
- Add text content of items[i][j] to the newly created element
tdElement.textContent = items[i][j]
You can also add classes to the HTML element created using the classlist.add method
Now you need to append the element to the parent node like you already did using the appendChild method.
Here's the MDN guide. Please go through it for a clearer understanding MDN docs
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kanuos |
