Το πρόβλημα
How to create whith javascript a button to create automatic tables (rows and columns)
How to create whith javascript a button to create automatic tables (rows and columns)
To create a javascript button with also stating the number of columns and rows, it can be done with the following code:
This code includes: custom row(s) input – custom column(s) input – deletion of top row
ps Rember to change the color of the table: default is #ff9966
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table Generator</title>
<style>
#myTable {
border-collapse: collapse;
margin-top: 20px;
}
#myTable td {
border: 1px solid #333;
padding: 8px;
background-color: #ff9966;
}
</style>
</head>
<body>
<p><b>Enter the number of rows and columns:</b></p>
<table>
<tr>
<th><label for="row">No. of Row(s)</label></th>
<th><label for="col">No. of Column(s)</label></th>
</tr>
<tr>
<td><input type="number" id="row" min="1" step="1"></td>
<td><input type="number" id="col" min="1" step="1"></td>
</tr>
</table>
<br>
<button type="button" onclick="createTable()">Create table</button>
<button type="button" onclick="deleteTopRow()">Delete top row</button>
<button type="button" onclick="location.reload()">Reload page</button>
<div id="tableContainer"></div>
<script>
function createTable() {
const rows = document.getElementById("row").valueAsNumber;
const cols = document.getElementById("col").valueAsNumber;
if (
!Number.isInteger(rows) || rows < 1 ||
!Number.isInteger(cols) || cols < 1
) {
alert("Please enter positive whole numbers for rows and columns.");
return;
}
const table = document.createElement("table");
table.id = "myTable";
for (let r = 0; r < rows; r++) {
const row = table.insertRow();
for (let c = 0; c < cols; c++) {
const cell = row.insertCell();
cell.textContent = `Row ${r + 1}, Col ${c + 1}`;
}
}
document.getElementById("tableContainer").replaceChildren(table);
}
function deleteTopRow() {
const table = document.getElementById("myTable");
if (!table || table.rows.length === 0) {
alert("There are no rows to delete.");
return;
}
if (confirm("Delete the top row?")) {
table.deleteRow(0);
}
}
</script>
</body>
</html>Σας βοήθησε αυτή η λύση;