Get Choice Field Type Values using ECMA Script

Leave a Comment
Hi All,

In a following post we will see about how to read “Choice” data type values. I have one Custom List and column with data type as “Choice” and have some values.


'use strict';

var SPAppWebUrl;
var spHostUrl;
var choiceValues;

(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 () {
        spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
        SPAppWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
        $('#btnGetValues').on('click', function () {
            GetChoiceValues();
        });
    });

    function GetChoiceValues() {
        var Context = new SP.ClientContext.get_current();
        if (Context !== undefined && Context !== null) {
            var parentContext = new SP.AppContextSite(Context, spHostUrl);
            var web = parentContext.get_web();
            //TestList is my list name
            var list = web.get_lists().getByTitle("TestList");
            var fldColl = list.get_fields();
            //choice type is my column of data type choice
            choiceValues = Context.castTo(list.get_fields().getByInternalNameOrTitle('choice_x0020_Type'), SP.FieldChoice);
            Context.load(choiceValues);
            Context.executeQueryAsync(ExecuteOnSuccess, ExecuteOnFailure);
        }
        function ExecuteOnSuccess() {
            var choices = choiceValues.get_choices();
            if (choices !== null) {
                $.each(choices, function (index, Val) {
                    alert(Val);
                });
            }
        }
        // This function is executed if the above call fails
        function ExecuteOnFailure(sender, args) {
            alert('Failed to get user name. 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]);
        }
    }
})();

NOTE: The above program has been executed in SharePoint Hosted App.

Thanks.

Related Post

0 comments:

Post a Comment