Monday, March 5, 2018

how to dynamically add and remove the Canada Post autocomplete in Javascript?

it is quite easy to enable the canada post autocomplete, we just need to follow the sample from Canada post autocomplete.

here is the sample code to initialize the Canada post autocomplete to a textbox with id "street-address"

 enableCanadaPostAutoComplete = function () {
        var fields = [
            {
                element: "street-address", field: "Line1"
            },
            {
                element: "street-address2", field: "Line2",
            },
            {
                element: "city", field: "City", mode: pca.fieldMode.PRESERVE
            },
            {
                element: "province", field: "ProvinceCode", mode: pca.fieldMode.POPULATE
            },
            {
                element: "postal", field: "PostalCode", mode: pca.fieldMode.PRESERVE
            },
            { element: "country", field: "CountryIso3", mode: pca.fieldMode.COUNTRY }
        ],
            options = {
                key: sci.CanadaPostKey,
            };

        control= new pca.Address(fields, options);
    }

if you want to remove the Canada post autocomplete feature from the input textbox, then i will show how make it work around

var canadaPostAutoCompleteControl = canadaPostAutoCompleteControl || {};

enableCanadaPostAutoComplete = function () {
        var fields = [
            {
                element: "street-address", field: "Line1"
            },
            {
                element: "street-address2", field: "Line2",
            },
            {
                element: "city", field: "City", mode: pca.fieldMode.PRESERVE
            },
            {
                element: "province", field: "ProvinceCode", mode: pca.fieldMode.POPULATE
            },
            {
                element: "postal", field: "PostalCode", mode: pca.fieldMode.PRESERVE
            },
            { element: "country", field: "CountryIso3", mode: pca.fieldMode.COUNTRY }
        ],
            options = {
                key:  myCanadaPostKey,
            };

        canadaPostAutoCompleteControl = new pca.Address(fields, options);
    }


disableCanadaPostAutoComplete = function () {
        if (canadaPostAutoCompleteControl) {
            canadaPostAutoCompleteControl.destroy();
        }
    }

you can call disableCanadaPostAutoComplete in the click event.

No comments:

Post a Comment