jQuery SPServices and autocomplete

21 Aug

On Codeplex the SPServices library is available. This is a jQuery library for SharePoint Web Services.
One of the functions available in the library is the SPAutoComplete:
http://spservices.codeplex.com/wikipage?title=%24%28%29.SPServices.SPAutocomplete  

The SPAutocomplete lets you provide values for a Single line of text column from values in a SharePoint list. The function is highly configurable and can enhance the user experience with forms.  

To use this function you have to put it on a new item form. On one of the fields of this new item form the SPAutoComplete can be implemented and used.  

To make this work, create a new blank webpart page. Open the page in SharePoint Designer and insert a dataview on the page. At the Data Source Library select the list you want to create a new item form for and select Show Data. Select the desired fields to show on the new item form and select Insert Selected Fields as … New Item Form. Save the page and edit the page in the browser.  

Imagine:
I have a list called Customers with a Title column with the name of the customer. In another list I need these names also but I want to suggest the user who adds a new item which customers we already have and how these are spelled.  

Let’s proceed.
Edit the page in the browser and add a Content Editor Webpart, modify the webpart and show the Source Editor to add some code.

<script type="text/javascript" src="../ICTLibrary/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../ICTLibrary/jquery.SPServices-0.5.4.min.js"></script>
 

<script type="text/javascript">
    $(document).ready(function() {
        $().SPServices.SPAutocomplete({
            sourceList: "Customers",
            sourceColumn: "Title",
            columnName: "CustomerName",
            numChars: 2,
            ignoreCase: true,
            slideDownSpeed: 100,
            debug: true
        });
    });
</script>

For all available options to set please take a look at the link provided earlier, but for the important ones here.
sourceList: the list to get the suggestions from
sourceColumn: the static column name to get the suggestions from
columnName: the displayname of the field in the new item form
You can hide the content editor webpart so you only see the new item form. Go ahead and type the first letters of a customername.

Ofcourse you want to use the autocomplete function on other pages or in other webparts and not only on a new item form.
For this purpose you can use the jQuery UI plugin (http://docs.jquery.com/UI/Autocomplete, implemented in release 1.8) in combination with the SPServices library.
With the SPServices library the items can be pulled out of the desired list and column and with the auto complete function of the jQuery UI the source can be set to the values to show.
To get the desired data from the list:

            $().SPServices({
                operation: "GetListItems",
                async: false,
                listName: "Customers",
                CAMLViewFields: '<ViewFields><FieldRef/></ViewFields>',
                CAMLQuery: '<Query><OrderBy><FieldRef Name=\'Title\' Ascending=\'True\' /></OrderBy></Query>',
                completefunc: function(xData, Status) {
                    $(xData.responseXML).find("[nodeName= z:row]").each(function() {
                        itemSource[k] = $(this).attr('ows_Title');
                        k = k + 1;
                    });
                }
            });

  

And use the gathered data in the input field at the page:

            $("input#autocompletebox").autocomplete({
                source: itemSource,
                minLength: 2
            });

Where ‘autocompletebox’ is the id of the input control:

<input id="autocompletebox" />

  

And the output of this all in the browser:

23 Replies to “jQuery SPServices and autocomplete

  1. I really love the way your site looks. I think it is awesome. If you dont mind me asking, what template is your blog? Thanks.

  2. A formidable share, I just given this onto a colleague who was doing somewhat analysis on this. And he in truth purchased me breakfast as a result of I discovered it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to debate this, I feel strongly about it and love reading extra on this topic. If doable, as you change into expertise, would you thoughts updating your weblog with more particulars? It is highly useful for me. Big thumb up for this blog publish!

  3. Hi,

    This is really nice feature and I am using it successfully. But does it work in cross sites. Say my target list is in another site collection and I want to fetch the records of a column from there. Will it work? The code is below and it doesnt work 🙁 am I misssing something ?

    $().SPServices.SPAutocomplete({
    WebURL: “/sites/AnotherSiteCollection”,
    sourceList: “ListName”,

    sourceColumn: “ID”,
    columnName: “Enter the No”,
    numChars: 1,
    ignoreCase: true,
    slideDownSpeed: 100,
    debug: true
    });

  4. 24. Heya i am for the first time here. I found this board and I find It truly useful & it helped me out a lot. I hope to give something back and aid others like you helped me.

  5. This is the reply I got, I am working on the same to make it working.

    “This ought to work, however, there are reasons why it wouldn’t. They generally boils down to authentication issues. As long as your user has access to the other Site Collection without any additional login, you should be OK. Windows Auth is always cleanest, of course.

    M”

  6. Hi,

    To test your scenario I created a site collection at the root of a web application and a sub site collection:
    sitecoll1: http://sitecoll1
    sitecoll2: http://sitecoll1/sites/sitecoll2

    On a page at sitecoll1 I put a CEWP with the following code:

            $().SPServices.SPAutocomplete({
                WebURL: "/sites/SiteColl2",
                sourceList: "Customers",
                sourceColumn: "Title",
                columnName: "magic2",
                numChars: 2,
                ignoreCase: true,
                slideDownSpeed: "fast",
                processingIndicator: "<img src='_layouts/images/REFRESH.GIF'/>",
                debug: true
            });
    

    and I create a div:

     <input id="autocompletebox" Title="magic2"/>
    

    At SiteColl2 I created a custom list Customers.
    As soon as I type something in the textbox I get results from the list on the other site collection.

    Represents this your scenario?

    Regards, Anita

  7. Does this allow the user to add a new item, that is currently not in the desired list. My issue: I want to suggest options for the person entering the information, but not restrict them from entering something that may not be included in the current list.

  8. Thanks for the feedback. I’m still learning.

    I’ve got Autocopmete working as your designed above in your original post. Awesome! I’d like autocomplete to provide all the list options that match the entered text, not just the options that start with that text. Per the Wiki you reference, in your article, from CodePlex. It seems like I need to include a CAMLQuery that will allow the autocomplete feature to display all list options that contain the typed text, not just list items that begin with the text. I’m just not sure about how to write the CAMLQuery into the below script. Could you provide an example or assistance?

    $().SPServices.SPAutocomplete({
    sourceList: “”,
    sourceColumn: “Company_Name”,
    columnName: “Company Name”,
    CAMLQuery: “”, <-?????
    CAMLQueryOptions: "”, <-??????
    filterType: "Contains",
    numChars: 0,
    ignoreCase: false,
    highlightClass: "",
    uniqueVals: false,
    slideDownSpeed: "fast",
    debug: false

  9. Hi Chris,

    You don’t have to include a CamlQuery(Options) if you don’t want to.
    The filterType, just like you used, will do the trick about the Contains in stead of BeginsWith. Remember that you have to set the sourceList to an existing list.

    Let me know if you have further questions.

    Regards, Anita

  10. Hi Anita,
    i like your post, as you provide good example and expand very well manner of “Marc Anderson’s SPService”.
    But i have some query regarding the using the external list in infopath 2010, as i not understand the how i can use jquery.
    so i simply try on normal form , it works fine there.
    then i tried this one code on simple cqwp.

    $(document).ready(function() {

    var itemSource=[];
    var k=0;

    $().SPServices({
    operation: “GetListItems”,
    async: false,
    listName: “Customer”,
    CAMLViewFields: “”,
    completefunc: function(xData, Status) {
    $(xData.responseXML).find(“[nodeName= z:row]”).each(function() {
    itemSource[k] = $(this).attr(‘ows_Title’);
    k = k + 1;
    alert(‘shi’);
    });
    }
    });
    $(“input#autocompletebox”).autocomplete({
    source: itemSource,
    minLength: 2
    });
    alert{‘hhi’);
    });

    But no success, please help me, i am waiting your reply.

  11. Hi Anita,

    I tried alot to accomplish the autocomplete the but its not working. below is the code i am using for your referrence.

    $(“#ctl00_PlaceHolderSearchArea_ctl01_S3031AEBB_InputKeywords”).keypress(function(event) {
    $().SPServices.SPAutocomplete({
    WebURL: “/sites/testsite/”,
    sourceList: “Transection List”,
    sourceColumn: “Title”,
    columnName: “Title”,
    numChars: 1,
    ignoreCase: true,
    uniqueVals: false,
    slideDownSpeed: “1000”,
    processingIndicator: “”, // NOTE: This option has been deprecated as of v0.6.0
    debug: false
    alert(“Key pressed”);
    });
    });

  12. Hi,

    Great post. I used the code below to autocomplete, notice I use SPFilterNode instead of find.

    $(document).ready(function()
    {
    var itemSource=[];
    var k=0;
    $().SPServices(
    {
    operation: “GetListItems”,
    async: false,
    listName: “{CDID09A0-6DID-481E-8ID4-48IDDBD4IDD2}”,
    CAMLViewFields: “”,
    completefunc: function(xData, Status)
    {
    $(xData.responseXML).SPFilterNode(“z:row”).each(function()
    {
    itemSource[k] = $(this).attr(“ows_City”);
    k = k + 1;
    });
    }
    });

    $(“input#fsearch”).autocomplete({
    source: itemSource,
    minLength: 2
    });
    });

  13. Have you tested this with several thousand rows of list data? I wonder how scalable it is if the list you are pulling from is very large?

  14. Pingback: Autocomplete on Sharepoint DropDownList Column | asphive

  15. Hi Anitha,
    Thanks for your really good post!
    I got autocomplete working, but
    1. if I set ‘uniqueVals’ to true, it is not working! It is showing duplicate values in typeahead.
    2. I’m not able to filter it by content type using “CAMLQuery”.
    Any idea why it is failing. Response will be highly appreciated.

    Regards, Ramesh.

  16. Hi Anita,

    Can you please let me know how we can load an image along with the autocomplete text. I need to display image along with the search text. It will be great if you can provide some thoughts on the same.

    Thanks
    Suresh A

  17. HI,
    Can you help me, i used the below code which is not working. Actually i tried it in custom web part page and added the below code in Content Editor Web part. Its urgent. Thanks in advance.

    $().SPServices({
    operation: “GetListItems”,
    async: false,
    listName: “{3C7AA585-EF47-41CD-B393-0AFAC6773BE2}”,
    CAMLViewFields: “”,
    completefunc: function(xData, Status) {
    $(xData.responseXML).SPFilterNode(“z:row”).each(function() {
    itemSource[k] = $(this).attr(‘ows_City’);
    k = k + 1;
    });
    }
    });

    $(“#ctl00_m_g_1a45138d_7169_4416_8b52_7a45c97cabc4_txtBuildingNumber”).autocomplete({
    source: itemSource,
    minLength: 1
    });

  18. hi
    I did the SPAutocomplete and its workes well in a standard list
    but its not work in a pages library
    how can I refer to the values of the pages library?
    thanks

  19. Hello,

    Does anyone have idea to implement auto sugesstion for sharepoint text filter.This auto sugesstion values should come form Sharepoint List column.
    Any help would be appreciated.

    Thanks,
    Harsha

Comments are closed.