wimdeblauwe/taming-thymeleaf-sources

Improve row removal in chapter 16

Opened this issue · 0 comments

Hi,
I tried to create a PR in the main repo, but I don't have the right permissions.
Here's a patch that improves the row deletion in chapter 16. It avoids "holes" in the list, even when deleting items in the middle.
I hope you like it.

diff --git a/chapter16/src/main/resources/templates/teams/edit.html b/chapter16/src/main/resources/templates/teams/edit.html
index 8ad3508..1e777e4 100644
--- a/chapter16/src/main/resources/templates/teams/edit.html
+++ b/chapter16/src/main/resources/templates/teams/edit.html
@@ -108,8 +108,22 @@
 
         <!-- tag::removeTeamPlayerForm[] -->
         function removeTeamPlayerForm(formIndex) {
-            const teamplayerForm = document.getElementById('teamplayer-form-section-' + formIndex);
-            teamplayerForm.parentElement.removeChild(teamplayerForm);
+            const teamPlayerForms = document.getElementById('teamplayer-forms');
+            const count = parseInt(teamPlayerForms.getAttribute('data-teamplayers-count'));
+            // We cannot delete the element while iterating, it will throw off the iterator
+            let toDelete = null;
+            for (const child of teamPlayerForms.children) {
+                const id = child.getAttribute('id');
+                // Using a simple substring, replace with a regex for more reliability
+                const sequence = parseInt(id.substring(24));
+                if (sequence == formIndex) {
+                    teamPlayerForms.setAttribute('data-teamplayers-count', count - 1);
+                    toDelete = child;
+                } else if (sequence > formIndex) {
+                    child.setAttribute('id', `teamplayer-form-section-${sequence - 1}`);
+                }
+            }
+            toDelete?.parentElement.removeChild(toDelete);
         }
 
         <!-- end::removeTeamPlayerForm[] -->