If your question had something to do with Java, I'd say that first you should move all these Java codes away from your JSP, as the purpose of a JSP is only to provide the output as a viewer component - it shouldn't have any business logic to be done with pure Java code.
For now, this question looks like more related to JavaScript - moving this to HTML/JavaScript forum.