Click here to Skip to main content
15,860,972 members
Articles / Productivity Apps and Services / Sharepoint / SharePoint 2013

Multiple form fields autocomplete for SharePoint 2010\2013 using JavaScript

Rate me:
Please Sign up or sign in to vote.
4.93/5 (6 votes)
2 Oct 2013CPOL5 min read 66.5K   12   18
This article describes how to implement autocomplete for multiple SharePoitn 2010\2013 form fields using JavaScript.

Introduction 

Filling forms could be painful sometimes, especially for forms with many fields. In this article I'll describe approach which can simplify forms filling significantly. In my case I needed to implement order form interface. In fact it contains a lot of fields I can prefill based on chosen customer, such as address, ZIP code and account number. All of this data is already stored in separate list called "Customers directory". 

Final requirements could looks like this:

When user starts typing in the customer field, I need to suggest list of customer names from Curtomers directory. When user chooses customer from suggestions list, I need to read data multiple field values from Customers directory and fill corresponding fields in the order form. User can correct filled values later if needed. 

To implement such functionality I used to use JavaScript and this case is not an exception. There are many reasons for this:  

  • It well fits Office 365 restrictions.
  • It easily migrates from older SharePoint versions.
  • It is easily to debug without slow SharePoint solution deployment.
  • REST SharePoint 2013 API or SPServices are almost such powerful as server code.
  • Finally I just like it. 

In this article I'll use SPServices jQuery plugin for communication with SharePoint services. It works for SharePoint 2013 as well as for SharePoint 2010. I'll also use jQuery UI Autocomplete plugin to implement suggestions functionality.

plumFormAutocomplete plugin works well for single field as much as for multiple fields.  Plugin supports text fields only.

Plugin in action looks like this:

How to use plumFormAutocomplete jQuery plugin 

You can use this plugin without looking into the code. Firstly, I'll describe how to use it, then if you still will be interested, you can look inside plugin implementation.

Prerequisites

If you don't have jQuery, jQuery UI or SPServices, you can download fresh version from official sites. For tutorial purposes I assume that names of downloaded files and folders are following:

  • jquery.min.js 
  • jquery.SPervices.min.js  
  • jquery-ui-1.10.3.custom.min.js
  • jquery-ui-1.10.3.custom.min.css
  • css folder for jQuery UI

I also assume that you have jquery.plumFormAutocomplete.js downloaded from source code of this article (Source code download link).

Upload jquery.min.js, jquery.SPServices.min.js, jquery-ui-1.10.3.custom.min.js and jquery.plumFormAutocomplete.js files to Style Library within your site collection. You also need to upload jQuery UI CSS styles located in the same folder with jquery-ui-1.10.3.custom.min.js. Then open New or Edit form, where autocomplete plugin will be used and add js and CSS links to placeholder PlaceHolderAdditionalPageHead.  You can use following snippet: 

ASP.NET
<SharePoint:ScriptLink runat="server" 
  Name="~SiteCollection/Style Library/jquery.min.js" Language="javascript"/>
<SharePoint:ScriptLink runat="server" 
  Name="~SiteCollection/Style Library/jquery.SPServices.min.js" Language="javascript"/>
<SharePoint:ScriptLink runat="server" 
  Name="~SiteCollection/Style Library/jquery-ui-1.10.3/jquery-ui-1.10.3.custom.
    min.js" Language="javascript"/>       
<SharePoint:ScriptLink runat="server" 
  Name="~SiteCollection/Style Library/jquery.plumFormAutocomplete.js" Language="javascript"/>        
<SharePoint:CSSRegistration name="<% $SPUrl:~SiteCollection/Style Library/
  jquery-ui-1.10.3/css/smoothness/jquery-ui-1.10.3.custom.min.css%>" runat="server"/>

Configure and call plugin  

Now you are ready to configure and call plugin. For my case plugin call looks like this:

JavaScript
//get control for autocomplete field
var fieldControl = $.getFieldControl('Title');
                
//call autocomplete plugin for field control
fieldControl.plumFormAutocomplete({
	sourceList: 'Customers directory',
	sourceMatchField: 'Title',
	labelFields: ['Title', 'ZIPCode'],
	labelSeparator: ', ',
	fillConcatenatedLabel: false,
	fieldsMapping: [{sourceField: 'Address', targetField: 'CustAddress'},
			{sourceField: 'AccountNumber', targetField: 'CustAccountNumber'},
			{sourceField: 'ZIPCode', targetField: 'CustZIPCode'}]
});

You can wrap plugin call inside jQuery $(document).ready() function to ensure that code will be executed after page is loaded.

Let us look at this code sample in more detail. Code is divided into two parts:

  1. Get control for autocomplete field
  2. Call autocomplete plugin for field control

For the first step you need to specify internal name of autocomplete field for getFieldControl function. It is 'Title' in my case.

In the second step you need to call plugin for received autocomplete field and configure plugin options. Plugin options are structured as a single object as any jQuery plugin options.

Plugin options

  • sourceList - name or GUID of source list, where suggestions will be taken. It is Customers directory in my case.
  • sourceMatchField - internal name of the field in the source list. This field will be used to find matching list items for autocomplete keywords.
  • labelFields - an optional parameter, you can specify source list field internal names array. All field values for these  fields will be concatenated with labelSeparator and displayed in autocomplete suggestion as a single string like this: Value1, Value2, ..., ValueN.
  • labelSeparator - an optional parameter, it is separator for labelFields concatenation, for example it could be comma with space (', ').
  • fillConcatenatedLabel - an optional parameter, set true if you need to fill autocomplete textbox with all concatenated labelFields values, set false if you need to fill autocomplete text box only with single field value.
  • fieldsMapping - an optional parameter, it is an array of field mapping objects. Each object declares mapping from source list field to target list field. In my case names of source and target fields are the same. For example Address in Customer directory and Address in Orders list.

Mapping object has following syntax:

JavaScript
{sourceField: 'Internal name of source field', targetField: 'Internal name of target field'}  

Note: You can specify only non optional parameters, plugin will work correctly. This plugin works well as single field autocomplete too, just do not fill optional parameters.

Plugin configuration without optional parameters could look like this:

JavaScript
fieldControl.plumFormAutocomplete({
    sourceList: 'Customers directory',
    sourceMatchField: 'Title'
});

Internal implementation of the plugin

Let us look at the full plugin source code. You can download it here.

There are three major part inside the code:

  1. Getting text field input. 
  2. Apply jQueryUIi autocomplete plugin and SPServices to get suggestions.
  3. Implementing helper functions.

To get field input I used jQuery selectors and simple regular expression. Unfortunately SharePoint doesn't provide any method to get field controls from JavaScript, it only stores field internal name inside html comment in the following format:

HTML
<!-- FieldName="Title"
FieldInternalName="Title"
FieldType="SPFieldText"
-->  

So, I had to parse it to find control I needed. Final function was added to jQuery:

JavaScript
//function gets text field control by internal name
$.getFieldControl = function (fieldInternalName) {
  var regexStr = 'FieldInternalName="' + fieldInternalName + '"'
  var regex = new RegExp(regexStr, 'i');
  var fieldCell = $('td.ms-formbody').filter(function () { 
    return (regex).test($(this).html()) 
  });
  return $(fieldCell.find('input')[0]);
} 

In the next step I applied jQuery UI autocomplete plugin and implemented source and select plugin functions. Source function calls source list using SPServices and CAML to get suggestions. When suggestion found, I store all mapped field values inside autcomplete object:

JavaScript
source: function (request, response) {
    var autocompleteVals = [];
    var k = 0;

    $().SPServices({
        operation: "GetListItems",
        async: false,
        listName: options.sourceList,
        CAMLViewFields: getViewFields(options.fieldsMapping),
        CAMLQuery: getCamlQuery(options.sourceMatchField, request.term),
        completefunc: function (xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function () {
                var queryResult = this;
                var fieldsValues = getFieldsValues(options.fieldsMapping, queryResult);                            
                var labelText = getLabelText(fieldsValues);
                autocompleteVals[k] = {
                    label: labelText,
                    value: options.fillConcatenatedLabel ? labelText  : 
                      extractFieldValue(fieldsValues, options.sourceMatchField), 
                    fieldsValues: fieldsValues
                };

                k++;
                
                function getLabelText(fieldValues){
                    var result = '';
                    if(options.labelFields){
                        for(i = 0; i < options.labelFields.length; i++)
                        {	                            		
                            var fieldName = options.labelFields[i];
                            var fieldVal = extractFieldValue(fieldValues, fieldName);
                            if(fieldVal != ''){
                            	if(i > 0){
                                	result += options.labelSeparator;
                            	}
                                result += fieldVal;
                            }
                        }	                            	
                    } else {
                         result += extractFieldValue(fieldValues, options.sourceMatchField);
                    }
                    return result;
                }
            });
            response(autocompleteVals);
        }
    });
}

Select function fills values inside mapped fields according to matched item from source lists. It reads values stored inside ui.item and fills corresponding fields based on suggestion selection.

JavaScript
select: function (event, ui) {
    //Fill all depended fields
    $.each(ui.item.fieldsValues, function () {
        var fieldVal = this;
        var fieldInput = $.getFieldControl(fieldVal.key);

        var outputVal = fieldVal.value;
        if (outputVal) {
            var lookupSeparator = ';#';
            if (outputVal.indexOf(lookupSeparator) != -1) {
                var ind = outputVal.indexOf(lookupSeparator);
                var length = lookupSeparator.length;
                var startInd = ind + length;
                outputVal = outputVal.substring(startInd, outputVal.lenght)
            }

            fieldInput.val(outputVal);
        }
    });
}

Maybe you discovered that there are three helper functions inside plugin: getFieldsValues, getViewFields, and getCamlQuery.

getFieldsValues parses SPServices response and fills autocomplete object according to specified fields mapping.

JavaScript
//get values for all mapped fields
function getFieldsValues(fieldsMapping, queryResult) {
    var result = [];
    $.each(fieldsMapping, function () {
        var fieldMapping = this;
        var val = $(queryResult).attr("ows_" + fieldMapping.sourceField)
        result.push({ key: fieldMapping.targetField, value: val, sourceKey: fieldMapping.sourceField});
    });
    
    var sourceVal = $(queryResult).attr("ows_" + options.sourceMatchField);
    result.push({ value: sourceVal , sourceKey: options.sourceMatchField});
    
    return result;
}

getViewFields generates ViewFields xml for CAML query according to fields mapping.

JavaScript
//get view fields for all mapped fields
function getViewFields(fieldsMapping) {
    var result = "<ViewFields>";
    var isSourceFieldAdded = false;

	if(fieldsMapping){
		$.each(fieldsMapping, function () {
            var mapping = this;
            var viewField = "<FieldRef Name='" + 
                    mapping.sourceField + "'/>";
            result += viewField;
        });
        
        isSourceFieldAdded = fieldsMapping.filter(function(){
				            	return this.sourceField == options.sourceMatchField;
    						 }).length > 0;
	}            
                
	if(!isSourceFieldAdded){			
		result += "<FieldRef Name='" + options.sourceMatchField + "'/>";
	}            
    
    result += "</ViewFields>";
    return result;
}

getCamlQuery generates CAML query according to filter column internal name and keyword from input.

JavaScript
//get CAML query for keyword
function getCamlQuery(colname, keyword) {
    var where = "<Where><Contains><FieldRef Name='" + colname + 
      "'></FieldRef><Value Type='Text'>" + keyword + 
      "</Value></Contains></Where>"
    var orderBy = "<OrderBy><FieldRef Name='" + colname + "' Ascending='True' /></OrderBy>"
    var query = "<Query>" + where + orderBy + "</Query>";
    return query;
}

Updates

03.10.2013

  • Additional optional parameters added: labelFields, labelSeparator, fillConcatenatedLabel.
  • Reading lookup fields from source list implemented. 
  • Minor bug fixes.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionUnable to find the source plumFormAutocomplete.js Pin
jeeva.chandru26-Sep-19 21:06
jeeva.chandru26-Sep-19 21:06 
AnswerRe: Unable to find the source plumFormAutocomplete.js Pin
Shival12-Mar-21 1:56
Shival12-Mar-21 1:56 
QuestionWhere to configuration? Pin
Member 1281310024-Oct-16 18:57
Member 1281310024-Oct-16 18:57 
BugIt works great, except for one important detail: On the matching values, the word "string#" shows in front of the names! Pin
Member 1209899729-Oct-15 13:43
Member 1209899729-Oct-15 13:43 
QuestionObject doesn't support this property or method Pin
ali.kiyani24-Jan-15 23:02
ali.kiyani24-Jan-15 23:02 
QuestionUsing this technique within "new/edit" forms for Document Sets and/or documents Pin
Ferdinando Simonetti3-Jan-15 4:02
Ferdinando Simonetti3-Jan-15 4:02 
AnswerRe: Using this technique within "new/edit" forms for Document Sets and/or documents Pin
ali.kiyani24-Jan-15 23:03
ali.kiyani24-Jan-15 23:03 
GeneralRe: Using this technique within "new/edit" forms for Document Sets and/or documents Pin
Ferdinando Simonetti25-Jan-15 2:37
Ferdinando Simonetti25-Jan-15 2:37 
QuestionCalling a list from a different site collection Pin
Member 1125000620-Nov-14 1:59
Member 1125000620-Nov-14 1:59 
QuestionSharePoint Foundation Pin
Member 1054265922-Jan-14 14:28
Member 1054265922-Jan-14 14:28 
QuestionCan't get the autocomplete to fire. Pin
ivanderu22-Jan-14 3:37
ivanderu22-Jan-14 3:37 
QuestionSource code Pin
KellyPapa1-Oct-13 20:35
KellyPapa1-Oct-13 20:35 
AnswerRe: Source code Pin
Anton Khritonenkov12-Oct-13 10:31
Anton Khritonenkov12-Oct-13 10:31 
GeneralRe: Source code Pin
KellyPapa2-Oct-13 19:31
KellyPapa2-Oct-13 19:31 
QuestionDrop down Pin
Member 103089261-Oct-13 3:39
Member 103089261-Oct-13 3:39 
AnswerRe: Drop down Pin
Anton Khritonenkov11-Oct-13 4:12
Anton Khritonenkov11-Oct-13 4:12 
QuestionSource Code Pin
progkix16-Aug-13 7:33
progkix16-Aug-13 7:33 
AnswerRe: Source Code Pin
Anton Khritonenkov116-Aug-13 10:03
Anton Khritonenkov116-Aug-13 10:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.