Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve row removal in chapter 16 #9

Open
carlosduclos opened this issue Feb 1, 2024 · 0 comments
Open

Improve row removal in chapter 16 #9

carlosduclos opened this issue Feb 1, 2024 · 0 comments

Comments

@carlosduclos
Copy link

carlosduclos commented Feb 1, 2024

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[] -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant