Skip to content

Instantly share code, notes, and snippets.

@rs77
Created July 23, 2024 11:45
Show Gist options
  • Save rs77/51f593fdad4ba699efa9e2929c13fd8f to your computer and use it in GitHub Desktop.
Save rs77/51f593fdad4ba699efa9e2929c13fd8f to your computer and use it in GitHub Desktop.
Copying table row with select statements and recasting the newly copied select statements using MetroUI
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdn.metroui.org.ua/current/metro.css">
</head>
<body>
<table class="table">
<thead>
<tr>
<th>Header</th>
<th>Header2</th>
</tr>
</thead>
<tbody id="journal-lines">
<tr>
<td>
<select data-role="select">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</td>
<td>
<select data-role="select">
<option>ABC</option>
<option>DEF</option>
<option>GHI</option>
</select>
</td>
</tr>
</tbody>
</table>
<div class="block mt-10">
<button onclick="appendJournalLine()" class="mr-2">
<span class="label">Copy Last Line</span>
</button>
</div>
<script src="https://cdn.metroui.org.ua/current/metro.js"></script>
<script>
const appendJournalLine = () => {
const tbody = document.querySelector('#journal-lines');
const lastRow = tbody.querySelector('tr:last-child');
const newRow = lastRow.cloneNode(true);
// Reset select elements in the new row to default or first option
newRow.querySelectorAll('td').forEach(td => {
td.querySelectorAll('select').forEach(
(select) => {
// Remove everything in the `td` - flushing out all the other Metro HTML
td.innerHTML = '';
// Append the select element back into the `td`
td.appendChild(select);
// !important!
Metro.makePlugin(select, 'select');
}
);
});
tbody.appendChild(newRow); // Append the new row to the table
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment