Autocomplete for text and people picker fields

You find updated documentation here

Change log
Always test a new version to see that it works as expected before adding it to a production environment.

You find the latest change log here: https://spjsblog.com/dffs/dffs-change-log/

May 19, 2016

I have released v1.4.3 with a new feature that lets you pre-filter the data-source with a CAML query. To do this, add a new key-value pair to the argument object like this (see more details below):

"filterCAML":"<Eq><FieldRef Name='Author' LookupId='TRUE' /><Value Type='Integer'><UserID/></Value></Eq>"

This example will show only items created by current user. You can provide any valid CAML.

March 20, 2016

I have released v1.41 with this bugfix:
I have fixed a bug occurring when using the new option to add  new values to the lookup list, and it is a “isLookupInSelf”. If you had already moved the cursor away from the autocomplete field so the field had the “error class”, going back to add it to the list did not clear this class so it appeared as if the error was still there. The value would however be saved to the list as it should.

February 19, 2016

I have released v1.4 with these new features:

  • Added option to add a custom function to parse the returned value before setting it using the “setFields” option. Here is an example (see parseFunction):
    spjs.ac.textField({
    "applyTo":"Project",
    "helpText":"Project name or number...",
    "listGuid":"ProjectList",
    "listBaseUrl":"/DFFS",
    "showField":"Title",
    "enforceUniqueValues":true, // New in v1.33
    "rowLimit":15,
    "listOptionsOnFocus":false,
    "reValidateOnLoad":false,
    "allowAddNew":false, // New in v1.4
    "isLookupInSelf":true, // New in v1.4
    "setFields":[
    {
    "fromFIN":"ProjectNumber",
    "toFIN":"PNumber",
    "parseFunction":"",
    "skipIfEmpty":false
    },
    {
    "fromFIN":"Created",
    "toFIN":"ProjectCreatedDate",
    "parseFunction":"parseDateFunc",
    "skipIfEmpty":false
    }
    ]
    });

    // This function converts the ISO8601 date returned from the query to a format ready for inserting in the field

    function parseDateFunc(a){
    // Set the desired format in the variable "f"
    var f = "MM/dd/yyyy hh:mm" , d = new Date(a);
    f = f.replace("MM",(d.getMonth()+1) < 10 ? "0"+(d.getMonth()+1) : (d.getMonth()+1));
    f = f.replace("dd",d.getDate() < 10 ? "0"+d.getDate() : d.getDate());
    f = f.replace("yyyy",d.getFullYear());
    f = f.replace("yy",d.getFullYear().toString().substring(2));
    f = f.replace("hh",d.getHours() < 10 ? "0"+d.getHours() : d.getHours());
    f = f.replace("mm",d.getMinutes() < 10 ? "0"+d.getMinutes() : d.getMinutes());
    return f.split(/ |:/);
    }
  • Added option to add new items to the autocomplete if you cannot find a match. Please look at the description of the parameters “allowAddNew” and “isLookupInSelf” below.

The autocomplete solution is part of the DFFS package, and you will find updated versions in the “plugins” folder in the DFFS download package, or in the “incrementalReleases” folder. Get the files here

February 09, 2016

I have released v1.33 with support for returning only unique values. You set this up in the argument object like this:

spjs.ac.textField({
	"applyTo":"Project",
	...
	"enforceUniqueValues":true, // New
	...
	...

The autocomplete solution is part of the DFFS package, and you will find updated versions in the “plugins” folder in the DFFS download package, or in the “incrementalReleases” folder. Get the files here

October 31, 2014

v1.31:
Fixed a bug with using single quotes in the lookup field.

May 1, 2014

v1.21:
Added event triggering for the fields set by “setFields” in the autocomplete function call – for use with DFFS “is changed” trigger.

April 25, 2014

v1.2:

  • Added option to prevent validation of the selected value on load. This will allow for duplicate entries in the lookup list. See function call example below for details.
  • Fixed a bug that prevented a selected people picker form being cleared.

April 6, 2014

v1.1: Added option to bypass the SP2013 check when applying the people picker autocomplete in SP2013. This must only be used when having SP2010 style people pickers with the “validate user” and “address book” icons.

To use this option, change the argument object like this:

spjs.ac.peoplePicker({
	"applyTo":"Responsible",
	"forceOn2013":true,
	...

I have previously posted a few solutions here and here, but those are old and does not work for new SharePoint versions.

I have redone the solution to bring it up to support SP2007, SP2010 and SP2013. This is a total remake that does not rely upon jQueryUI for the autocomplete part.

In this example, I have added autocomplete to the single line of text field “Project”, and to the single choice people picker “Responsible”.
IMG

Here I have started typing in the Project field:
IMG
You can use this solution with single line of text columns and single choice people picker columns. I have not built in support for multi choice people pickers.

Please note that this solution is made for unmodified SharePoint forms (NewForm and EditForm) and will not work for custom forms modified in SPD or InfoPath. It will however play nice with DFFS.

The people picker autocomplete is not available in SP 2013 as this version already have this built in.

How to set it up
  1. If you don’t have jQuery already, get it here
  2. Get the latest version of spjs-utility.js from here.
  3. Download the file “spjs-autocomplete.js” from here.
  4. Add the code below the form in NewForm and EditForm as described below.
Setup for a single line of text column

Add this code below the form web part in NewForm and EditForm using a HTML form Web Part, Script Editor or link to a file containing the code from a Content Editor Web Part using the content link option.

<script type="text/javascript" src="/Scripts/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="/Scripts/spjs-utility/spjs-utility.js"></script>
<script type="text/javascript" src="/Scripts/Autocomplete/spjs-autocomplete.js"></script>
<script type="text/javascript">
var fields = init_fields_v2();

spjs.ac.textField({
	"applyTo":"Project",
	"helpText":"Project name or number...",
	"listGuid":"ProjectList",
	"listBaseUrl":"/test",
	"showField":"Title",
	"optionDetailFields":"[], // New in v 1.4.12
	"enforceUniqueValues":true, // New in v1.33
	"rowLimit":15,
	"listOptionsOnFocus":false,
	"minLengthBeforeSearch":3, // New in v 1.4.12
	"reValidateOnLoad":false,
	"allowAddNew":false, // New in v1.4
	"isLookupInSelf":false, // New in v1.4
	"filterCAML":"", // New in v1.4.3
	"multiselect":true, // New in v1.4.4. If this is true, the "setFields section will not apply",
	"multiselectSeparator":"; ", // New in v1.4.4.
	"orderBy":[{"fin":"Title","ascending":true}], // New in v1.4.5
	"setFields":[
		{
			"fromFIN":"ProjectNumber",
			"toFIN":"PNumber",
			"parseFunction":"",
			"skipIfEmpty":false
		}
	]					
});					
	
</script>
Options explained:
  • applyTo: The FieldInternalName of the field to add autocomplete to.
  • helpText: The text in the autocomplete field when it is empty
  • listGuid: The list GUID or the display name of the list you are pulling the options from.
  • listBaseUrl: The base url of the list. For a subsite named “Test”, this is the correct base url: “/test”. For the root site, use an empty string like this: “”.
  • showField: This is the field to show in the autocomplete.
  • optionDetailFields: Additional fields to show more details in the drodown.
  • enforceUniqueValues new in v1.33: true or false to only return unique values.
  • rowLimit: This is the max number of items to pull back. Use a low number to keep the query lightweight and fast.
  • listOptionsOnFocus: true or false determines whether or not to pull in the first batch when the field gets focus. Setting this to true will mimic a dropdown with an arrow to the right.
  • minLengthBeforeSearch: This settings controls how many characters the user needs to enter before the search is triggered.
  • reValidateOnLoad new in v1.2: true or false to determine whether or not to validate the selection when loading the form in EditForm. If this is set to true, you cannot have duplicates in the lookup list, and if you delete an item in the lookup list, the selected value will be invalid when you edit an item that has this value selected.
  • allowAddNew new in v1.4: true or false to specify whether or not to allow adding new values to the “dataset”. If you set the below “isLookupInSelf” parameter to false, you MUST use the GUID in the parameter “listGuid” above.
  • isLookupInSelf new in v1.4: Used with the above “allowAddNew” parameter. Use true or false to specify whether or not the autocomplete is a lookup in the the current list. Please note that setting this to false is only supported in SharePoint 2013. This will open a dialog for adding the new item.
  • filterCAML new in v1.4.3: Add your own CAML here to prefilter the data-source. You can use an valid CAML – for example this to get items created by current user:
    "filterCAML":"<Eq><FieldRef Name='Author' LookupId='TRUE' /><Value Type='Integer'><UserID/></Value></Eq>",
  • setFields: This in an array of objects containing additional fields to pull in and set based on the selection. It has these properties:
    • fromFIN: The FieldInternalName of the field in the list you are pulling from.
    • toFIN: The FieldInternalName of the field in the list you are writing to.
    • parseFunction: This is used to parse the returned value before inserting it in the “toFIN” field. See example on parsing a date value in the change log in the top of this page (February 19, 2016).
    • skipIfEmpty: true or false determines whether or not to skip this option if this field is empty.
Setup for a single choice people picker

Add this code below the form web part in NewForm and EditForm using a HTML form Web Part, Script Editor or link to a file containing the code from a Content Editor Web Part using the content link option.

<script type="text/javascript" src="/Scripts/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="/Scripts/spjs-utility/spjs-utility.js"></script>
<script type="text/javascript" src="/Scripts/Autocomplete/spjs-autocomplete.js"></script>
<script type="text/javascript">
var fields = init_fields_v2();

spjs.ac.peoplePicker({
	"applyTo":"Responsible",
	"forceOn2013":false,
	"helpText":"Enter name or email address...",
	"showField":"Title",
	"enforceUniqueValues":true, // New in v1.33
	"chooseFromUserGroup":null,
	"showUsersOnly":true,
	"rowLimit":5,
	"listOptionsOnFocus":false,
	"reValidateOnLoad":false,
	"setFields":[
		{
			"fromFIN":"EMail",
			"toFIN":"ResponsibleEmail",
			"parseFunction":"",
			"skipIfEmpty":false
		}
	]
});
	
</script>
Options explained:

The shared options are explained in the previous section.

  • chooseFromUserGroup: If you want to limit the selection to a specific user group, add the name or the ID here. The ID must be added as an integer. Leave as null to search all users. Please note that you cannot let the autocomplete search among all users while the people picker itself (in the list settings) is restricted to a certain group.
  • showUsersOnly: true or false determines whether or not to show users and groups, or users only.
Override the labels and text

Add this to the CEWP code (above the function call to spjs.ac.peoplePicker or spjs.ac.textField) to override the standard texts. Translate as you like.

spjs.ac.text = {
	"imgTitle":"The list of valid choices is updated automatically when you type",
	"noItems":"No items match your search",
	"addNewItem":"Add {0} to the list?",
	"noValidItems":"No valid items match your search",
	"invalid":"Invalid value",
	"moreItemsLabel":"Showing the first {0} items",
	"moreItemsMouseover":"Continue typing to narrow your search",
	"searching":"Searching for: "
};
How to use this with DFFS

To use this with DFFS you must add the script reference to “spjs-autocomplete.js” in the CEWP code for DFFS, and wrap the function call like this:

function dffs_Ready(){
	spjs.ac.peoplePicker({
		"applyTo":"Responsible",
		"helpText":"Enter name or email address...",
		"showField":"Title",
		"enforceUniqueValues":true, // New in v1.33
		"chooseFromUserGroup":null,
		"showUsersOnly":true,
		"rowLimit":5,
		"listOptionsOnFocus":false,
		"reValidateOnLoad":false,		
		"setFields":[
			{
				"fromFIN":"EMail",
				"toFIN":"ResponsibleEmail",
				"parseFunction":"",
				"skipIfEmpty":false
			}
		]
	});
}

You can also add the function call to the Custom JS section in the Misc tab. In this case you do not wrap it in dffs_Ready().

Post any bugs or feedback in the comments below.

Alexander

44 thoughts on “Autocomplete for text and people picker fields”

  1. Hi Alex,

    I’m trying to set this up for a People Picker field on a SP2007 new form with DFFS. The solution seems to be loading fine but when i try entering a name into the field it keeps returning no results?

    I’m running the latest versions of DFFS, Jquery and Utility.

    Thanks for your help.

      1. Hi Alex,

        Here your go:
        function dffs_Ready(){
        spjs.ac.peoplePicker({
        “applyTo”:”AssignedTo”,
        “helpText”:”Enter name or email address…”,
        “showField”:”Title”,
        “chooseFromUserGroup”:null,
        “showUsersOnly”:true,
        “rowLimit”:10,
        “listOptionsOnFocus”:false,
        “setFields”:[
        {
        “fromFIN”:”EMail”,
        “toFIN”:”AssignedToEmail”,
        “skipIfEmpty”:false
        }
        ]
        });
        }

      2. Sorry for the late reply. I cannot see any obvious errors. Are you you using the code on a subsite or on the root site?

        Any errors in the developer console (hit f12 in IE)?

        Alexander

  2. Brilliant!!, but this would be more efficient if could apply to multi select People picker!!

  3. Hi again, I am getting a “You must upgrade to spjs-utility 1.181 or above” error, but I’m certain that that’s the version I am calling. I call it from the masterpage, and its the only version in my SiteAssets library. I cleared my browser cache and also tried multiple browsers, but all get that error message. Am I doing something wrong? Thanks!

    1. Also should mention, I have dffs on the page, and I get the error whether I use the Custom JS section in the dffs configuration, or if I put in on the page wrapped in the dffs_Ready() function.

    2. Hi,
      Could it be that the order of the scripts is wrong? spjs-utility.js must be called after jQuery, but before all other scripts.

      You can try alerting this to verify the version:

      alert(spjs.utility.version);

      Alexander

  4. You can actually use the Sharepoint 2010 people picker with Sharepoint 2013. Many custom form solutions do. Is there a way to turn off the check for SP 2013?

  5. Hi Alexander,

    Below is the function I wrap into the custom JS section of the DFFS, but it says error. Can you help me figure it out ?

    spjs.ac.textField({
    “applyTo”:”CLINIQUE”,
    “helpText”:”Tapez le nom de la clinique”,
    “listGuid”:”Adresses”,
    “listBaseUrl”:” “,
    “showField”:”Title”,
    “rowLimit”:5,
    “listOptionsOnFocus”:false,
    “reValidateOnLoad”:false,
    “setFields”:[
    {
    “fromFIN”:””,
    “toFIN”:””,
    “skipIfEmpty”:false
    }
    ]
    });

    Thanks

    1. Hi,
      If you are not using “setFields” you must leave it as an empty array like this:

      "setFields": []

      I hope this helps.
      Alexander

  6. Hi, how if i want use the autocomplete for text in project server which apply to project custom field? i have tried
    to change apply to using my project custom field. but it didn’t work. do you have any suggestion?

    spjs.ac.textField({
    “applyTo”:”myprojectcustomfield”,

  7. Hi Alex,

    This is a very handy solution indeed, great work!!!
    But is there any way I can make this possible for multi select PPL picker fields??? I really need it.

  8. Hi Alex,

    Before using this tweak, a normal PPL picker shows field’s description right below the PPL picker field. But when I use your control, the description is not visible anymore.
    Please advise.

  9. Hi Alex,

    First of all many thanks for the very useful solution.
    Secondly, I was wondering if there’s any way this solution would be able to support the custom Data Form WP. Maybe I can tweak the code myself with your guidance of course.
    Please I urgently need this.

    1. Hi,
      You are free to modify the code if you want to have a go at it, but I unfortunately do not have the time to help you with this.

      Alexander

  10. Hey, Love your solutions, thanks for keeping us SP2007 peeps in mind 🙂

    Question: This solution works great, I am using the “set Fields” to copy and set a date picker. Problem, and the date is being reformatted to a date that the picker will not accept.

    Example: “07/31/2014” to “2014-07-31 08:00:00”

    any chance of a sugestion for an easy fix for that?

  11. Nevermind, easy fix. (It’s called I read what you designed this for :D). After reading through your post 5 times, again I see that this is only for text and People picker.

    Easy fix, change the date into text :), make a calculated column that grabs the date and changes it to text.
    Create a calculated column, put in this formula =([column.name],”mm/dd/yyyy”), make sure to set the data type returned as text.

    Make the auto fill pull form this calculated column and Viola! – this solution now works for autofilling date fields! 🙂

  12. Hi Andrew,
    Great tool and is working beautifully with DFFS 4.0.
    Have you considered adding a flag to prevent ‘applyto’ field validation when the field loses focus. Effectively reproducing the “Allow ‘Fill-in’ choices” functionality but with an Autocomplete.

    1. Hi,
      Do you mean like a button you could click to turn it into a text field? If this is not an active choice I’m afraid you will get problems with “half” values being added to the field.

      Alexander

  13. Hi Andrew, thats not quite what I meant. Here’s an example of what I mean: I’ve got a list item with a ‘title’ textField which autocompletes to existing ‘title’ textFields in sibling list items in the same list. But since its a textfield I can keep typing and create something new. Sometimes you might want to use the same title, sometimes you just want to change it slightly by appending it. An autocomplete which doesn’t enforce/validate selection (after autocompleting) gives the user the benefits of selecting an existing ‘title’ and then modifying it slightly if desired.

  14. Hi Alex,

    I have a standard edit form with a single line text field. Want to look up an application key and corresponding name i store on a separate list containing just just the two fields I mentioned.

    Script for this:

    var fields = init_fields_v2();

    spjs.ac.textField({
    “applyTo”:”AppAttribCI”,
    “helpText”:”Enter a CI Name”,
    “listGuid”:”23A03F4C-62C5-4DA5-8545-7489FD8DEEF0″,
    “listBaseUrl”:”/PAM”,
    “showField”:”Title”,
    “rowLimit”:15,
    “listOptionsOnFocus”:true,
    “reValidateOnLoad”:false,
    “setFields”:[
    {
    “fromFIN”:”CommonAppName”,
    “toFIN”:”Title”,
    “skipIfEmpty”:true
    }
    ]
    });

    I have tried everything I can think of but keep on getting the following error displayed in red under the text field I am trying to enable when I click the drop down arrow or type in it:

    Ensure the list “23A03F4C-62C5-4DA5-8545-7489FD8DEEF0” exists on “/PAM”, and that the field “Title” does exist in that list.

    The “Title” field referred to in the error maps to what I put in the “showField” variable .

    I have checked over and over and this list, URL and Field does exist on the source list.

    The lists.asmx web services call returns a 500 error when the auto complete call goes out. (The lists.asmx service works just fine for everything else)

    The request HTTP grabbed with fiddler:

    Request URL: https://xxxxxxxxxxxxxx.com/PAM/_vti_bin/lists.asmx
    Request Method: POST
    Status Code: 500
    Form Data
    ‘1.0’ encoding=’utf-8′?>23A03F4C-62C5-4DA5-8545-7489FD8DEEF0SAP P07-010 MDM [PROD]15FALSE

    I do not have access to the server logs, so cannot debug server side…

    Any ideas what I can try next?

    K

      1. Never mind, I had to fully qualify the listBaseUrl variable and now it works. Not sure why I could not just provide the relative path as describe in your setup instructions.

        It is now working…..

  15. Hi Alex. I want auto complete multiple fields with differents values through the title field’s value, not just one, How can I do it? For example: In my list I have Title, Code, Value and Description. By the value of the title, I want to automatically complete the other fields too, not just one.

  16. Hi Alexander,
    I am trying to fill the Raised by and Responsible fields in my DFFS NewForm with the current user using rules.
    If I use the default MS PeoplePicker the name is not validated and I get an error on Save unless I click on the Check Names button first.
    If I use SPJS Autocomplete the field does not appear to get populated using the DFFS rule.
    If I use a text field type I can use the SP ‘Default Value’ =[Me] (but gives me the wrong name property).
    My ideal would be a SPJS Autocomplete field that I can populate with a DFFS rule and not have to validate/click afterwards. Is this possible? Many thanks

  17. Alex i am trying to query list of numbers from the diffrent list and use Single text of field Auto complete, I added script into content editor webpart but have been getting following error in console “TypeError:spjs.ac is undefined. ” How do i fix this issue.

    var fields = init_fields_v2();
    spjs.ac.textField({
    “applyTo”:”Title”,
    “helpText”:”Please Enter Number…”,
    “listGuid”:”Numbers”,
    “listBaseUrl”:”/services”,
    “showField”:”Number”,
    “rowLimit”:15,
    “listOptionsOnFocus”:true,
    “reValidateOnLoad”:false,
    “setFields”:[]
    });

  18. You were right one of the script file was not loaded up correctly. I fixed the issue now i am getting error: The field “Title” could not be found. But i have that column in the list Numbers where my Where i am getting info to display in this showfield” Number”

Comments are closed.