how to handle the table.
plese reference this site.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table Insertion and Update</title>
<style>
table {
width: 50%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: center;
}
</style>
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr data-key="1">
<td>1</td>
<td>One</td>
</tr>
<tr data-key="3">
<td>3</td>
<td>Three</td>
</tr>
<tr data-key="5">
<td>5</td>
<td>Five</td>
</tr>
<tr data-key="7">
<td>7</td>
<td>Seven</td>
</tr>
<tr data-key="9">
<td>9</td>
<td>Nine</td>
</tr>
</tbody>
</table>
<button onclick="insertRow(4, 'Four')">Insert Key 4</button>
<br><br>
<label for="currentKey">Current Key:</label>
<input type="number" id="currentKey">
<label for="newKey">New Key:</label>
<input type="number" id="newKey">
<button onclick="updateKey()">Update Key</button>
<script>
function insertRow(key, value) {
const table = document.getElementById('myTable');
const tbody = table.querySelector('tbody');
const newRow = document.createElement('tr');
newRow.setAttribute('data-key', key);
newRow.innerHTML = `<td>${key}</td><td>${value}</td>`;
const rows = Array.from(tbody.querySelectorAll('tr'));
let inserted = false;
for (let i = 0; i < rows.length; i++) {
const currentKey = parseInt(rows[i].getAttribute('data-key'));
if (key < currentKey) {
tbody.insertBefore(newRow, rows[i]);
inserted = true;
break;
}
}
if (!inserted) {
tbody.appendChild(newRow);
}
}
function updateKey() {
const currentKey = parseInt(document.getElementById('currentKey').value);
const newKey = parseInt(document.getElementById('newKey').value);
const table = document.getElementById('myTable');
const tbody = table.querySelector('tbody');
const rows = Array.from(tbody.querySelectorAll('tr'));
let rowToUpdate = null;
for (let i = 0; i < rows.length; i++) {
const key = parseInt(rows[i].getAttribute('data-key'));
if (key === currentKey) {
rowToUpdate = rows[i];
break;
}
}
if (rowToUpdate) {
rowToUpdate.setAttribute('data-key', newKey);
rowToUpdate.cells[0].innerText = newKey;
const newValue = rowToUpdate.cells[1].innerText;
tbody.removeChild(rowToUpdate);
insertRow(newKey, newValue);
}
}
</script>
</body>
</html>