This is my solution.
Note that I've been mostly a back-end guy recently; I've not done javascript for a long while.
I broke out the javascript from the HTML page since that was the object of my attention. I needed to be able to easily validate the behavior as I refactored.