Get Lookup Column Value using ECMA Script

Leave a Comment
Hi All,
In a following post we will see how to get Look up Id and Values from the List using ECMA Script in Apps.

Please find the below Code Snippet.

'use strict';

    var SPAppWebUrl;
    var spHostUrl;

    (function () {
        // This code runs when the DOM is ready and creates a context object which is
        // needed to use the SharePoint object model
        $(document).ready(function () {
            //getUserName();
            spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
            SPAppWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
            $('#btnGetLookup').on('click', function () {
                getLookUp();
            });
        });
        function getLookUp() {
            var context = SP.ClientContext.get_current();
            if (context !== undefined && context !== null) {
                var parentContext = new SP.AppContextSite(context, spHostUrl);
                var web = parentContext.get_web();
                //Name of the child List.
                var list = web.get_lists().getByTitle("MyList");
                //get the List Item by passing the List Item ID.
                var listItem = list.getItemById(2);
                context.load(listItem);
                context.executeQueryAsync(ExecuteOnSuccess, ExecuteOnFailure);
            }
            function ExecuteOnSuccess() {
                var lookup = listItem.get_item("LookupColumnName");
                alert("Lookup Id: " + lookup.get_lookupId() + "\n Lookup Value: " + lookup.get_lookupValue());
            }
            function ExecuteOnFailure(sender, args) {
                alert('error' + args.get_message());
            }
        }

        function getQueryStringParameter(urlParameterKey) {
            var params = document.URL.split('?')[1].split('&');
            var strParams = '';
            for (var i = 0; i < params.length; i = i + 1) {
                var singleParam = params[i].split('=');
                if (singleParam[0] == urlParameterKey)
                    return decodeURIComponent(singleParam[1]);
            }
        }

    })();

Thanks.

Related Post

0 comments:

Post a Comment