Thursday, April 22, 2010

Using SPList as Datasource for jQuery UI Autocomplete

A client recently wanted an auto complete field populated with a SharePoint list. Luckily, the jQuery UI library recently added an auto complete widget to their offering. So with the widget and SharePoint's ability to expose SPList data as xml we have a robust solution at our fingertips.

First, lets look at SharePoint's underutililized feature of exposing lists as xml through the url. That's right, use the right url and your list comes back as xml.  Here's the format

"#WEBURL#/_vti_bin/owssvr.dll?Cmd=Display&List={#LISTGUID#}&Query=Title%20Name&XMLDATA=TRUE"

Replace #WEBURL# with url of your site.
Replace #LISTGUID# with your list's guid.
The "Query=Title%20Name" limits the fields coming back to "Title" and "Name". These are the internal field names, one more reason not to use spaces in your field names.

These are really only the basics of what you can do with this techinque, the rest can be found here. URL Protocol

Next, you will need jQuery version 1.4.2 and jQuery UI version 1.8.0. You can either download these from their sites or use the Google cdn. Take a look here about adding the jQuery library and code into SharePoint if you need to. Use the code below and you have an input box with auto complete feed by a list. Pretty cool.

  <script type="text/javascript">     
           (function(){
                 var xmlSource = "#WEBURL#/_vti_bin/owssvr.dll?Cmd=Display&
                                  List={#LISTGUID}&Query=Title%20Name&XMLDATA=TRUE";

                 $.ajax({
                    url: xmlSource,
                    dataType: "xml",
                    success: function(xmlResponse) {
                        var data = $("z\\:row", xmlResponse).map(function() {
                            return {
                                title: $(this).attr("ows_Title"),
                                name: $(this).attr("ows_Name")
                            };
                        }).get();
                        $("#auto").autocomplete({
                            source: data,
                            minLength: 1,
                            select: function(event, ui) {
                                var title = ui.item.title;
                                var name = ui.item.name;
                           //TO DO what to do with the values that have been selected
                            }
                        });
                    }
                })//end .ajax

            }) //end function
  </script>

<input id="auto" type="text" />


This solution could be wrapped in a custom field control. If you were to do this you may be able to do away with lookup fields and provide auto complete everywhere in your site.

1 comment:

  1. Alternatively, take a look at using the SharePoint Web Services. I have a simple autocomplete function in my SPServices jQuery library.

    M.

    ReplyDelete