How To: Filter Lookup Field Values by Current User

I had been struggling with SharePoint 2007 trying to get the current user’s ID using SPServices and jQuery. I wanted to filter results based on a SharePoint user lookup field in a custom list. The issue I was struggling with, using SPServices, was that I wasn’t able to get the current user ID. I’m not sure, but I think it’s because I’m still using SharePoint 2007.

However, I stumbled across this solution which didn’t require me to know the ID of the user. And it worked like a charm (with one small change).

var userName = $().SPServices.SPGetCurrentUser({ fieldName: "Name" });
var query = '<Query>' +
                '<Where>' + 
                    '<Eq>' +
                        '<FieldRef Name="SharePointUser" />' +
                            '<Value Type="User">' + userName + '</Value>' +
                    '</Eq>' +
                '</Where>' +
    operation: "GetListItems",
    async: false,
    listName: "UserAccessList",
    CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
    CAMLQuery: query,
    completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("z:row").each(function() {
            // will return only results that match the current logged in user
            // in the 'SharePointUser' column