Tuesday, November 22, 2011

JSP - Javascript

Using javascript in JSP is no different from using it in HTML.

Update your HelloWorld.jsp with the following:
 <html>  
      <head>  
           <script type="text/javascript">  
                function ageCheck()  
                     {  
                          year = parseInt(document.getElementById("birthdate").value.substring(0,4));  
                          if (year > 1995)  
                               alert("You are underage!");  
                          else  
                               alert ("You may enter!");  
                     }  
           </script>       
      </head>  
      <body>  
           Enter your birthday (yyyy-mm-dd): <input type="text" id="birthdate" onblur="ageCheck()"/>  
      </body>  
 </html>  


We have an edit field which takes a birthday, then calls a javascript function to check for underage.

Run Ant:dist to rebuild HelloWorld.war, then deploy it to Tomcat.
You may need to restart Tomcat after cleaning the previous HelloWorld.

Point your browser to http://localhost:8080/HelloWorld/jsp/HelloWorld.jsp

Enter your birthdate, then tab out of the edit field to trigger the javascript function.

(The javascript function is attached to the onblur event, so tabbing out of the edit field triggers it.)

No comments: