Saturday, November 25, 2017

jQuery Cascading Dropdown in SharePoint

jQuery Cascading Dropdown in SharePoint

Step 1: Create "Countries" List.
Step 2: Create "Regions" List with "Country" as a lookup column from "Countries" List.
Step 3: Create "States" List with "Country" as a lookup column from "Countries" List and "Region" as a lookup column from "Regions" List.
Step 4: Create "CascadeDropdownsList" List with with "Country" as a lookup column from "Countries" List , "Region" as a lookup column from "Regions" List and "State" as a lookup column from "States" List.
Step 5: Create script file "SPCascadeDropdowns.html" and add below code to this file. finally upload this file into "/SiteAssets/CascadeDropdowns/SPCascadeDropdowns.html".
SPCascadeDropdowns.html:-
<!DOCTYPE html>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("nobr:contains('Region')").closest('td').next('td').find('select').attr('disabled', 'disabled');
    $("nobr:contains('Region')").closest('td').next('td').find('select').find('option').remove().end().append('<option value="0">(None)</option>').val('0');
    $("nobr:contains('State')").closest('td').next('td').find('select').attr('disabled', 'disabled');
    $("nobr:contains('State')").closest('td').next('td').find('select').find('option').remove().end().append('<option value="0">(None)</option>').val('0');
    var CountryPrevValues = null;
    var RegionPrevValues = null;
    $("nobr:contains('Country')").closest('td').next('td').find('select').change(function() {
        var str = "";
        str$("nobr:contains('Country')").closest('td').next('td').find('select option:selected').text().trim();
        if(str.trim() != "(None)")
        {
            $("nobr:contains('Region')").closest('td').next('td').find('select').removeAttr("disabled");
            if(CountryPrevValues != str.trim() )
            {
                CountryPrevValues = str.trim();
                RetrieveRegionsDataUsingCountryValue(str.trim());
                $("nobr:contains('Region')").closest('td').next('td').find('select').find('option').remove().end().append('<option value="0">(None)</option>').val('0');
                $("nobr:contains('State')").closest('td').next('td').find('select').attr('disabled', 'disabled');
                $("nobr:contains('State')").closest('td').next('td').find('select').find('option').remove().end().append('<option value="0">(None)</option>').val('0');
            }
        }
        else
        {
            $("nobr:contains('Region')").closest('td').next('td').find('select').attr('disabled', 'disabled');
            $("nobr:contains('Region')").closest('td').next('td').find('select').find('option').remove().end().append('<option value="0">(None)</option>').val('0');
            $("nobr:contains('State')").closest('td').next('td').find('select').attr('disabled', 'disabled');
            $("nobr:contains('State')").closest('td').next('td').find('select').find('option').remove().end().append('<option value="0">(None)</option>').val('0');
        }
    }).trigger("change");   
    $("nobr:contains('Region')").closest('td').next('td').find('select').change(function() {
        var str = "";
        str = $("nobr:contains('Region')").closest('td').next('td').find('select option:selected').text().trim();  
        if(str.trim() != "(None)")
        {
            $("nobr:contains('State')").closest('td').next('td').find('select').removeAttr("disabled");
            if(RegionPrevValues != str.trim() )
            {
                RegionPrevValues = str.trim();
                RetrieveStatesDataUsingRegionValue(str.trim());
                $("nobr:contains('State')").closest('td').next('td').find('select').find('option').remove().end().append('<option value="0">(None)</option>').val('0');
            }
        }
        else
        {
            $("nobr:contains('State')").closest('td').next('td').find('select').attr('disabled', 'disabled');
            $("nobr:contains('State')").closest('td').next('td').find('select').find('option').remove().end().append('<option value="0">(None)</option>').val('0');
        }
    }).trigger("change");   
});
function RetrieveRegionsDataUsingCountryValue(CountryValue) {
    var objHeaders = {
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose"
        },
        mode: 'cors',
        cache: 'default',
        credentials: 'include'
    }
    fetch(_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Regions')/items?$filter=Country/Title eq '"+CountryValue+"'&$select=ID,Title,Country/ID,Country/Title&$expand=Country&$orderby=ID", objHeaders)
    .then(function (response)
    {
        return response.json()
    })
    .then(function (json) {
        var results = json.d.results;  
        $("nobr:contains('Region')").closest('td').next('td').find('select').find('option').remove().end().append('<option value="0">(None)</option>').val('0');
        results.map(function (item, key) {  
            $("nobr:contains('Region')").closest('td').next('td').find('select').find('option').end().append('<option value='+item.ID+'>'+item.Title+'</option>');       
        })
    })
    .catch(function (ex) {
        console.log('parsing failed', ex)
    })
}
function RetrieveStatesDataUsingRegionValue(RegionValue) {
    var objHeaders = {
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose"
        },
        mode: 'cors',
        cache: 'default',
        credentials: 'include'
    }
    fetch( _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('States')/items?$filter=Region/Title eq '"+RegionValue+"'&$select=ID,Title,Region/ID,Region/Title&$expand=Region&$orderby=ID", objHeaders)
        .then(function (response)
    {
        return response.json()
    })
    .then(function (json) {
        var results = json.d.results;  
        $("nobr:contains('State')").closest('td').next('td').find('select').find('option').remove().end().append('<option value="0">(None)</option>').val('0');
        results.map(function (item, key) {  
            $("nobr:contains('State')").closest('td').next('td').find('select').find('option').end().append('<option value='+item.ID+'>'+item.Title+'</option>');       
        })
    })
    .catch(function (ex) {
        console.log('parsing failed', ex)
    })
}
</script>
</head>
<body>
</body>
</html>

Step 6:  In "CascadeDropdownsList" List click on 'New' button to create new item. Then "NewForm.aspx" form will open. Now Edit the page and add "Content Editor Web Part (CEWP)"
and give Script URL as below. Save and Stop edit the page.
Step 7: Test the result. In "CascadeDropdownsList" List click on 'New' button to create new item. Then "NewForm.aspx" form will open. 

No comments:

Post a Comment