Auto complete text box in Salesforce

Auto completion of text box is an important feature to be added in many projects.
Use the below codes in your project for auto completion of text box in Salesforce.

Apex Class:

Name: autoCompleteController

global class autoCompleteController 
    global static SObject[] findSObjects(string obj, string qry, string addFields, string profilename) 
        /* More than one field can be passed in the addFields parameter
           Split it into an array for later use */
        List<String> fieldList=new List<String>();
        if (addFields != '')  
        fieldList = addFields.split(',');
        /* Check whether the object passed is valid */
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
        Schema.SObjectType sot = gd.get(obj);
        if (sot == null) 
            return null;
        /* Creating the filter text */
        String filter = ' like \'%' + String.escapeSingleQuotes(qry) + '%\'';
        /* Begin building the dynamic soql query */
        String soql = 'SELECT Name';
        /* If any additional field was passed, adding it to the soql */
        if (fieldList.size()>0) 
            for (String s : fieldList) 
                soql += ', ' + s;
        /* Adding the object and filter by name to the soql */
        soql += ' from ' + obj + ' where name' + filter;
            //profile name and the System Administrator are allowed
            soql += ' and Profile.Name like \'%' + String.escapeSingleQuotes(profilename) + '%\'';
            system.debug('Profile:'+profilename+' and SOQL:'+soql);
        /* Adding the filter for additional fields to the soql */
        if (fieldList != null) 
            for (String s : fieldList) 
                soql += ' or ' + s + filter;
        soql += ' order by Name limit 20';
        system.debug('Qry: '+soql);
        List<sObject> L = new List<sObject>();
            L = Database.query(soql);
        catch (QueryException e) 
            system.debug('Query Exception:'+e.getMessage());
            return null;
        return L;

Apex Component:

Name: autoComplete

<apex:component controller="autoCompleteController">

  <!-- JQuery Files -->

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

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

  <apex:stylesheet value="{!URLFOR($Resource.jqueryui18,'css/smoothness/jquery-ui-1.8.18.custom.css')}"/>

  <!-- Attributes Required For Component -->

  <apex:attribute name="objectname" description="The object name you want to look for." type="String" required="true"/>

  <apex:attribute name="additionalfield" description="Any additional fields you'd like to search and include in the display." type="String" required="false"/>

  <apex:attribute name="profilename" description="To filter on the basis of profile name and include in the display." type="String" required="false"/>

  <apex:attribute name="autocomplete_textbox" description="The ID for the Autocomplete List Textbox." type="String" required="true"/>

   <!-- CSS Style -->


    .ui-autocomplete-loading {background: white url({!$Resource.loadingIcon}) right center no-repeat;}


  <!-- Javascript -->

  <script type="text/javascript">

    var j$ = jQuery.noConflict();



        var sObjects;

        var queryTerm;


            minLength: 1,

            source: function(request, response) {

                        queryTerm = request.term;

                        autoCompleteController.findSObjects("{!objectname}", request.term, "{!additionalfield}", "{!profilename}", function(result, event){

                            if(event.type == 'exception')



                            } else


                                 sObjects = result;





            focus: function( event, ui ) {

                    j$(esc('{!autocomplete_textbox}')).val( ui.item.Name );

                    return false;


            select: function( event, ui ) {

                        j$(esc('{!autocomplete_textbox}')).val( ui.item.Name );

                        j$(esc('{!autocomplete_textbox}_lkid')).val( ui.item.Id );

                        j$(esc('{!autocomplete_textbox}_lkold')).val( ui.item.Name );

                        if (event.keyCode == 13) {



                        return false;



         .data( "autocomplete" )._renderItem = function( ul, item ) {

            var entry = item.Name;

            if("{!additionalfield}" !='')


                j$.each("{!additionalfield}".split(",") , function(key, value) {

                    entry = entry + " " + item[value];



            //entry = entry + "</a>";

            //entry = entry.replace(queryTerm, "<b>" + queryTerm + "</b>");

            entry = entry.replace( new RegExp( "(" + queryTerm + ")" , "gi" ), "<strong>$1</strong>" );

            return j$( "<li></li>" )

                .data( "item.autocomplete", item )

                .append( "<a>" + entry + "</a>")

                .appendTo( ul );



    function esc(myid)


           return '#' + myid.replace(/(:|\.)/g,'\\\\$1');




Static Resource:

Add a gif format loading image in Static resources with the name 'loadingIcon'.

Download jqueryui18 file from the below link

which is to be added in Static Resources.

Visualforce Pages examples:

Example for <apex:inputText>:

<apex:inputText value="{!memName}" id="membNam" >
<c:autoComplete autocomplete_textbox="{!$Component.membNam}" objectname="Member__c" />

Example for <apex:inputfield>:

<apex:inputfield value="{!Member__c.Name}" id="memNam">
        <c:autoComplete autocomplete_textbox="{!$Component.memNam}" objectname="Member__c" />



  1. I have a small problem. When I use the additional field, my drop down list has the Name field, but the additional field comes in as 'undefined'.

    Any idea what that means?

  2. Did u add in Static Resources.

  3. I'm using the following:


    I tried emailing you, but it failed.

  4. also, the additional field is a relationship field. Will this work with relationship fields?

  5. Nevermind I found a better Solution.

    I used a component that has no Controller.
    The Component receives a JSON String.

    That JSON String works with the AutoComplete found on this website:

  6. Getting Error jquery is not defined??

    1. Upload the jquery file in Static Resources from


  7. If I want to use for multiple fields where I need to add in code

  8. I am getting bellow script error while i am using in IE browser but it is working fine in Chrome and Firefox.
    I have included all jqueryui18 what mentioned in this blog.Can any one help me in this issue.
    Error Bellow:
    Unable to get value of the property 'open': object is null or undefined
    VFRemote.js, line 40 character 398

  9. HI,

    Its working fine for me.:)

    I want to remove focus from textbox after selecting value from autocomplete.
    What should I do.?
    Thanks in advance

  10. HI Magulan D,

    I am getting ' & ' displayed as '" & " And for single Qoute as " &quoete " . I deployed this to my Production environment and Getting Issues, help me urgent Please, I have used string replacement approaches in Jquery and Still getting (on Focus and Select Events).

    1. I have Special Characters like "-&# " in My Record names for Account and Other Objects. Those are Encrypted as &amp etc.

  11. Thanks alot buddy...It worked for me :-)