Home Visual Force Using jQuery in a Visualforce Page

Prerequisites

You will need to download the jQuery and jQuery UI libraries. jQuery is the core library which offers DOM manipulation methods and jQuery UI is a higher level library which constructs widgets for use on your page. From the jQuery UI site, you can download a zip tailored to the portions of the libraries you need. Once you have the ZIP in hand, you’ll need to upload it as a static resource. See Creating a Consistent Look and Feel with Static Resources to see specifics on uploading and using a static resource with your Force.com application.
For the purposes of the code in this recipe, we’ll assume you’ve named the static resource “jQuery”. To access jQuery in your Visualforce pages, you then need to include the libraries with something like this:

value="{!URLFOR($Resource.jQuery, '/js/jquery-1.4.2.min.js')}"  />
value="{!URLFOR($Resource.jQuery, '/js/jquery-ui-1.8.6.custom.min.js')}"  />
value="{!URLFOR($Resource.jQuery, '/css/ui-lightness/jquery-ui-1.8.6.custom.css')}"  />

About Using jQuery

To use jQuery within Force.com, you'll need to make use of the jQuery.noConflict() function to reassign jQuery's global variable to something which won't conflict with any other libraries which may already be in use (including standard, native libraries used within Visualforce). You'll see an example of this in the code below.
With jQuery, you typically locate an element based on a CSS selector, attach it to an event or widget, and then perform a specific function. Take this example:

$j = jQuery.noConflict();
$j("#phone").dialog({ autoOpen: false, modal: true, position: 'center'  });

This instructs jQuery to find an element with the id of "phone", create a dialog widget from it and set the initial parameters.
It's a best practice to make use of the onReady event of jQuery to initialize your JavaScript. This event will fire when DOM elements are ready, but before assets like images download. So for example, you'd write something like this:

$j(document).ready(function() {   /* …. Your actions …. */ }

A Code Sample

Here's a complete code sample. Assuming you've followed the pre-requisites, simply create a new Visualforce page with this source:

 
 
 
 
 
 

         
   
  
         account.name}','{!account.Phone}')">account.name}"/>
       
  

      

Phone:

  

    
 
 

You may also like

Leave a Comment