Using jQuery in Visualforce

Sharing is Caring

jQuery is one of the most utilized JavaScript libraries and can be easily be integrated into any visualforce page regardless of whether it’s meant for your internal users or on a force.com site. jQuery is usually used for manipulating elements in the DOM, animation or even event handling. Usually, I use it for doing some in page validation on form fields, so that we don’t have to post back to the server to find out if something is valid or not.

Before jQuery can be used in the visualforce page, it needs to be referenced. I recommend using the script hosted on a CDN by either jQuery or google or Microsoft. If you are interested in using Google’s, you can find it on the google developers site.

Here’s how to include it in the page (if using Google’s CDN):

<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js />

If you decide to host jQuery yourself, you’ll need to do something like the following. Your value could be different, I’m assuming you’ve uploaded into a static resource called “scripts.zip” which has jQuery named as jQuery.js.

<apex:includeScript value="{!URLFOR($Resource.scripts, '/jQuery.js')}" />

After including jQuery, we need to put jQuery in no conflict mode because Salesforce uses Prototype and references the $ sign. Usually, I assign j$ to be used instead of simply typing jQuery instead of $.

<script> j$ = jQuery.noConflict(); </script>

And now, whenever you want to use jQuery in the javascript in your visualforce page you will need to use j$ instead.

Here’s an example of how to do it:

j$(function() { doSomething(); });

instead of

$(function() { doSomething(); }

Note: it’s best to avoid duplicating code in each page, so consider doing this in a custom visualforce component or using a visualforce master page.

And finally, always set an id or class on any element that you would want to reference in javascript. The engine that converts visualforce components into actual html mangles the ids quite a bit. It’s easiest to make use of the attribute ends with method because the managled ids contain special characters that need to be escaped.

Example Element:

<apex:inputText value="{!account.Name}" id="acc_Name" />

To reference the example element, you would then need to do the following:

j$('[id$=acc_Name]')

Hope this helps!

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.