You should probably add a second loop on the bottom of the page to add that part, making sure to reset your loop to the first record so it can run again.
The code may need to appear after the "</form>" tag, since it manipulates the form onsubmit code, which may be why it won't work when added to the loop inside it.
It could also be a problem with your syntax or a missing <script> tag when you are writing it to the page.