Wednesday, July 9, 2014

How to create cascaded drop down using Client Side Object Model in SharePoint 2010 or above.

When we are trying to cascade drop-downs usually we use server side cascading which causes Post back and reload of controls View-state. Which leads to reset of fields to avoid it we used to use update panel. So instead of doing it we can use client side ECMA Script to get these values. It will make it more user friendly.

Here I am considering we have drop-down list bound from a list which works as a Parent List for second drop-down with a look-up column. We will call these methods on the first  drop-down change event :

function getDocumentType(index, sourceColumn, listName) {
        // get the list by it's name from the root site level
        var Query = '<View><Query><Where><Eq><FieldRef Name="' + sourceColumn + '" LookupId="TRUE"/><Value Type="Lookup">' + index + '</Value></Eq></Where></Query></View>';
        // Get the current client context to start. Most things run from the client context.
        clientContext = new SP.ClientContext.get_current();
        var myList = clientContext.get_site().get_rootWeb().get_lists().getByTitle(listName);
        // use a standard syntax CAML query to filter your results and the fields returned if required, by adding the following, or passing parameters to the load command below
        var query = new SP.CamlQuery();
        // You can leave out this line if you just want to return the entire list.
        // add your query to the getItems command for your list
        this.collListItems = myList.getItems(query);
        // issue the load command, these can be batched for multiple operations
        // execute the actual query against the server, and pass the objects we have created to either a success or failure function
        clientContext.executeQueryAsync(Function.createDelegate(this, this.mySuccessFunction), Function.createDelegate(this, this.myFailFunction));

    function mySuccessFunction() {
        var destDropDown= this.document.getElementById('<%=ddChild.ClientID%>');
        destDropDown.options.length = 0;
        var listItemEnumerator = this.collListItems.getEnumerator();
        var count = this.collListItems.get_count();
        destDropDown.options[destDropDown.options.length] = new Option("-Select-", "0");
        if (count != 0) {
            while (listItemEnumerator.moveNext()) {
                var currentItem = listItemEnumerator.get_current();
                destDropDown.options[destDropDown.options.length] = new Option(currentItem.get_item(destColumn).get_lookupValue(), currentItem.get_item(destColumn).get_lookupId());


    function myFailFunction() {
        alert("Error: Failed to fetch items. Please contact your Administrator.");
        // do something to alert the user as to the error here.

We can make these function generic for multiple level of cascading.