How To Implement JQuery AutoComplete
JQuery Autocomplete enhances the UI functionality of visualforce page, when a user types in a field it quickly find and select from a pre-populated list of values, leveraging searching and filtering. We can achieve this functionality by using Jquery with Ajax or by using custom controller in Salesforce.
Here is example in which i am using both option's, Account is coming from the controller and the contact records that we are getting is by using Ajax.
Code for Controller:
public class AutoCompleteJQueryController{
//list which returns accounts records
public list getAccountRecords(){
return [select id,name from account limit 25];
}
}
<!-- Javascript/JQuery Links--> <script src="https://code.jquery.com/jquery-1.8.2.js"></script> <script src="/soap/ajax/26.0/connection.js" type="text/javascript"></script> <script src="https://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<apex:page controller="AutoCompleteJQueryController">
<!-- Javascript/JQuery Links-->
<script src="https://code.jquery.com/jquery-1.8.2.js"></script>
<script src="/soap/ajax/26.0/connection.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css"/>
<script type="text/javascript">
var j$ = jQuery.noConflict();
var autoAccountList =[];
//use the <!-- <apex:repeat > --> tag to assign controller List values to javascript variable.
<apex:repeat value="{!AccountRecords}" var="accList">
//Store the name of the account in the array variable.
autoAccountList.push('{!accList.name}');
</apex:repeat>
// Establish a connection with salesforce database using the sforce.connection.init(sessionID, ServerURL) function.
var sessionId = '{!$Api.Session_ID}';
var server = "https://" + window.location.host + "/services/Soap/u/26.0";
sforce.connection.init(sessionId, server);
//Here we query the contact object using the sforce.connection.query function. This will return 200 results.
var result = sforce.connection.query("select Name from Contact");
var records = result.getArray("records");
var ContactList =[];
//Traverse the list of contact and store the value in javascript array variable which will then assign those values to the source of the autocomplete.
for(i=0;i<records.length;i++){
ContactList[i]=records[i].Name;
}
//on Document ready
j$(document).ready(function(){
j$("#accountAutocomplete").autocomplete({
source : autoAccountList
});
j$("#ajaxContactAutocomplete").autocomplete({
source : ContactList
});
});
</script>
<apex:form >
<b>Account(This list is coming from the Apex class)</b><input type="text" id="accountAutocomplete"/><br/><br/>
<b>Contact(This list is coming from salesforce's ajax toolkit)</b><input type="text" id="ajaxContactAutocomplete"/>
</apex:form>
</apex:page>