Thursday, June 10, 2010

jQuery should be easy to implement

The social-network-driven portal based on LifeRay is still under development. (Read here and here)

LifeRay uses jQuery intensively. I was tidying up the Contact Us page yesterday. This page is a static HTML page and has nothing to do with LifeRay.




But in the pursuit for consistent look-and-feel, I decided that validation of the form and display of success/error messages should be the same as what one will experience when he logs into LifeRay portal. So jQuery is the way to go!


The Contact Us form is so simple, yet it took me a long while to make it work using jQuery.





Maybe I'm too old for new technology. Ha! :) I could not find a good example on the web of the 2 things I want to achieve. 

The 2 things are so simple, mind you. 
1. Validate fields once "Submit" button is clicked
2. If the fields are valid, perform a form submission

Difficult? 

I struggled for quite some time and finally found the solution.


The codes below should be good enough for 80% of JavaScript developers and should be able to digest and implement in 5 mins. 


1. jQuery Scripts Download
  • Download the latest copy of jQuery from here. (rename the script as jquery-latest.js)
  • Download the latest copy of  jQuery plugin: Validation from here. (rename the script as jquery.validate.js)

2. Insert the following script between the head HTML tags



That's it. Done!


Do you need to write special code in the form section for jQuery to kick into effect? No.

Take a look at my form. There is no reference to jQuery at all.



The following is what you will see if there is an error.







PS: The tricky part for me is how to perform a form submission. Should be form.submit(); and not $("#myForm").submit();



.

No comments:

Post a Comment