Using jQuery In Salesforce Visualforce

Using jQuery In Salesforce Visualforce

Hello There! Welcome Back

Today, we are gonna learn how to use jQuery in Salesforce Visualforce.

You might be asking what is it or why are we using jQuery in the first place.

jQuery is a small, fast, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a lot of browsers.

Next, Why use it in Salesforce Visualforce ? Because, when we build visualforce pages on Salesforce Force.com platform, we use JavaScript to add functionality. However, referencing visualforce page elements in JavaScript with Hierarchy ID Structure(like page:form:input) OR $Component Selectors is not that straightforward when we are coding a lot in JavaScript.

This is where jQuery comes to the rescue. jQuery not only removes our concern for the Hierarchy Structure but it also helps us enhance our JavaScript Code and handle changes to our page elements and structure easily, enabling us to write less code and do more stuff on the page.

So, Lets get started !

Step 1:

Let's download the jQuery file from here and upload it onto your static resources and call it using this :

<apex:includeScript value="{!URLFOR($Resource.JQuery, 'js/jquery-1.11.1.min.js')}" />

Or else

The easy part is just to include the CDN like this :

<script src=“https://code.jquery.com/jquery-1.11.1.min.js”></script>

Step 2: MOST IMPORTANT

This is Because there are other libraries that make use of the same global variable name (“$”) that jQuery uses by default — Force.com’s default interface commonly includes at least one such library. Considering this issue, combining jQuery with Force.com interfaces can cause a conflict on the client side. This is the solution.

Add this right after the beginning of your script tag.

Step 3: Selectors

The jQuery ID Selector for Visualforce looks like this:

This selector will always find our page element, regardless of how we change the page hierarchy. It works because the ID will always end in ‘userInput’ once the Visualforce code is compiled into HTML. And we never have to worry about changes to our page structure. In addition, we can use the excellent additional features the jQuery library provides.

OR

you can even select the element by its class name like this:

Here is a small example code that shows how it goes with Visualforce and HTML. Copy and paste the below code into your Visualforce Page and Save and Get Going!

So, There it is we just learnt how to use jQuery in Visualforce. Explore all the great features the jQuery library provides here.

If you like the content, give it some sharing :)