Address Auto-Complete

For any integration, there are two pieces of JavaScript that you need: our JavaScript library and some configuration code. See the tutorial for more details on how to add this code to the page containing your address form.

JavaScript Library

Link to the JavaScript library:

<script src="https://cc-cdn.com/generic/scripts/v1/cc_c2a.min.js"></script>

There are two options for adding the JavaScript library:

Firstly, we host the final, compacted code on a CDN. This means that to add the JavaScript library to your page, you simply need to include this linkopen in new window. We recommend that you use this option, as you will automatically receive updates and bug fixes. However, if you use subresource integrity checksopen in new window, these will fail after an update.

Alternatively, you can download the JavaScript and host it on your own server.

Basic Configuration Options

These are the basic configuration options that should be included as part of any integration.

KeyTypeValuesRequiredDefaultDescription
accessTokenstringYour 20 digit code✔️Using the API requires a 20 character access token, which you should insert here. You will receive an access token when you sign up for an account.
domobjectContains elements to which search is applied✔️This is an object with DOM element references. By default, it finds elements by name, but this can be changed using domMode.
domModestringProperty to use to select element: name, id, class or objectnameSpecifies how the elements are passed in to the ‘dom’ object. For example, if this is set to 'id’, you would set the values in the 'dom’ object to the IDs of the form elements.

Example of basic configuration options:

new clickToAddress({
    accessToken: 'xxxxx-xxxxx-xxxxx-xxxxx', // Replace this with your access token
    dom: {
        search:     'search_field', // 'search_field' is the name of the search box element
        line_1:     'addr_line1',
        line_2:     'addr_line2',
        company:    'addr_company',
        town:       'addr_town',
        postcode:   'addr_postcode',
        county:     'addr_county',
        country:    'addr_country'
        // Other available fields: latitude, longitude, post_office_reference_1
    },
    domMode: 'name' // Use names to find form elements
});

Form Elements

Below is a list of the elements that can be included in the dom object.

The value that each property is set to will be the name, id or class of the element, or the object itself, depending on how the domMode is set. If domMode is not set, element names will be used.

KeyTypeRequiredDescription
searchstring✔️Input box for address search
line_1stringAddress line 1 element
line_2stringAddress line 2 element
companystringCompany element
townstringTown/city element
postcodestringPostcode/ZIP element
countystringCounty/state/province element
countrystringCountry element
latitudestringLatitude element
longitudestringLongitude element
post_office_reference_1stringRoyal Mail UDPRN (UK only)

Note

You will not be able to use latitude and longitude unless geocodes have been enabled on your access token. Please contact us at support@fetchify.com and we will enable geocodes for you.

Advanced Configuration Options

These are additional configuration options. None of these are required; if these options are not set then the default value will be used.

Search Box Interface

KeyTypeValuesDefaultDescription
gfxModeinteger1: The search interface is displayed below the address search box, 2: The search interface surrounds the search box1Sets the way the search interface is displayed.
styleobjectSee the colors section for more details.This object contains options for primary and secondary colors for the search interface.
cssPathstringA file pathThe default CSS file on our CDNThis is the path to the main CSS file that is used for the search box interface. If not using our CDN, be careful to set the cssPath. We recommend using an absolute URL.
placeholdersbooltrue, falseUse HTML placeholders on input boxes. (set by texts object).
textsobjectSee the texts section for more details.List of texts to use for placeholders and labels in the search interface.
showLogobooltrue, falsetrueOption for showing the clickToAddress logo on the search interface.
historyToolsbooltrue, falsetrueShow history navigation arrows. These allow a user to go 'back’ and 'forward’ through their search history, meaning the user can view previous search results from an earlier query.
defaultCountrystringAny ISO_2 or ISO_3 country code.gbrThis option allows you to manually change the default country for the address search. This is the country that will be selected for the user at initialization. For this option to work, getIpLocation must be set to false.
getIpLocationbooltrue, falsetrueUses the server to fetch the end-user’s country from the IP address. This country is then selected for the user at initialization. This option will override defaultCountry unless it is set to false.
countrySelectorbooltrue, falsetrueEnable/disable the list of countries in the search interface. If this is disabled, address search will only work for the default country.
enabledCountriesarrayArray of stringsAll countriesThis allows you to restrict the address search to only include certain countries. Only countries in the array are enabled. If the array is not set or empty, all countries are allowed. The format of the strings in the array is set by the countryMatchWith option.
countryMatchWithstringiso_3: will match countries to ISO_3 codes in enabledCountries array, iso_2: will match countries to ISO_2 codes in enabledCountries array, text: fuzzy match to any country detail in enabledCountries arrayiso_3How the enabledCountries are set. This sets the format of the strings in the enabledCountries array.
countryLanguagestringen, deenSet the language for the country list in the search interface.
disableAutoSearchbooltrue, falsetrueDisables searching as the user types. This can allow the search to be performed manually (for example, by clicking on a button) after the user has entered the search query.
limitToMaxLengthobjectenabled (boolean), useEllipsis (boolean)false for both optionsThis setting applies to the company field, town, and lines 1 and 2 of the address. It will truncate the address data we add to a field according to its maxlength attribute. useEllipsis will insert an ellipsis character at the end of the value. Warning: the ellipsis character may not be compatible with certain database systems. Please check for compatibility with your database before using this feature. You should also check with any third parties that handle the address data. This may include your fulfilment centre or delivery couriers. If in doubt, set useEllipsis to false.
transliteratebooltrue, falsefalseThis option will convert the search result(s) to Latin script. For example, if the address retrieved is "Ανατολικης Θρακης 9, 156 69 Παπαγος", it will be transliterated to "Anatolikis Thrakis 9, 156 69 Papagos".
useCeremonialCountiesbooltrue, falsefalseThis option instructs the library to use ceremonial counties in retrieved UK addresses.

Example using the interface configuration options:

new clickToAddress({
    accessToken: 'xxxxx-xxxxx-xxxxx-xxxxx', // Replace this with your access token
    dom: {
        search:     'search_field', // 'search_field' is the name of the search box element
        line_1:     'addr_line1',
        line_2:     'addr_line2',
        company:    'addr_company',
        town:       'addr_town',
        postcode:   'addr_postcode',
        county:     'addr_county',
        country:    'addr_country'
        // Other available fields: latitude, longitude, post_office_reference_1
    },
    domMode: 'name', // Use names to find form elements
    gfxMode: 1, // Display interface below search box
    style: {
        ambient: 'light', // Use white as main interface color
        accent: 'default' // Use default secondary color for interface
    },
    // Use a custom CSS file
    cssPath: 'https://yoursite.com/your_asset_folder/clicktoaddress/cc_c2a.min.css',
    placeholders: true, // Show placeholders
    texts: {
        default_placeholder: 'Start with post/zip code or street',
        country_placeholder: 'Type here to search for a country',
        placeholder_country_overrides: {},
        country_name_overrides: {},
        country_button: 'Change Country',
        generic_error: 'An error occurred. Please enter your address manually',
        no_results: 'No results found',
        more: '{{value}} more'
    },
    showLogo: true, // Show Address Auto-Complete logo
    historyTools: true, // Show arrows
    defaultCountry: 'gbr', // Sets the default country to the UK
    getIpLocation: true, // Sets default country based on IP
    countrySelector: true, // Country list is enabled
    enabledCountries: ['gbr', 'usa', 'can'], // Enabled countries are the UK, USA and Canada
    countryMatchWith: 'iso_3', // enabledCountries uses ISO_3 codes
    countryLanguage: 'en', // Country list displayed in English
    disableAutoSearch: false, // Auto-search is enabled
    limitToMaxLength: {
        enabled: false,
        useEllipsis: false // Note: This feature may not be compatible with certain database systems
    },
    transliterate: false, // Converts non-Latin script search results to Latin script
    useCeremonialCounties: false, // UK only
});

Events

These functions are executed at certain times and can be used to override basic functionality.

Function nameParametersDescriptionExample usage
onResultSelectedclass object, dom object, result objectExecuted after the results are filled in.Use to directly store the result data in an object, send it immediately via Ajax, or to reveal new parts of a form when an address is selected.
onSetCountyclass object, dom object, county objectExecuted instead of filling the county input element.Use to handle unique county options with special values, to handle cases where special jQuery events need to be triggered, or where the county may need to be filled in multiple places.
onErrorcode, messageExecuted when an error occurs.Use where you might want to react to errors in a special way. For example, reveal a form part, or even to detect initialization issues.
onSearchFocusclass object, dom objectExecuted when the address search input field has focus.Use to hide part of the form or reveal form fields when the search box is clicked.
beforeFindclass object, dom object, result objectExecuted before the find request.Use to alter the search text before the search is performed.
beforePopulateclass object, dom object, result objectExecuted before the address fields are populated.Use to alter part of the address before the fields are filled.
requestFunctionclass object, dom object, action string, parameters object, callback functionExecuted before a call is made to our API.Use to perform any action with the available data, e.g. using our new API or a relay server.

Example of configuration including functions executed on an event:

new clickToAddress({
    accessToken: 'xxxxx-xxxxx-xxxxx-xxxxx', // Replace this with your access token
    dom: {
        search:     'search_field', // 'search_field' is the name of the search box element
        line_1:     'addr_line1',
        line_2:     'addr_line2',
        company:    'addr_company',
        town:       'addr_town',
        postcode:   'addr_postcode',
        county:     'addr_county',
        country:    'addr_country'
        // Other available fields: latitude, longitude, post_office_reference_1
    },
    domMode: 'name', // Use names to find form elements
    onResultSelected: function(c2a, elements, address){
        // Perform any action here with the available data.
        // For example, you could reveal all the form fields when the fields are filled.
    },
    onSetCounty: function(c2a, elements, county){
        // Perform any action here with the available data.
        // You may want your own function to change the county, depending on your checkout.
    },
    onError: function(code, message){
        // Perform any action here with the available data.
        // For example, you may want to reveal the form fields if there is an error.
    },
    onSearchFocus: function(c2a, elements){
        // Perform any action here with the available data.
        // For example, you may want to hide part of the form when the search box is selected.
    },
    beforeFind: function(c2a, elements, parameters) {
        // Perform any action here with the available data.
        // For example, you may want to alter the search text before the search is performed.
    },
    beforePopulate: function(c2a, elements, address) {
        // Perform any action here with the available data.
        // For example, you may want to alter part of the address before the address fields are filled.
    },
    requestFunction: function(c2a, elements, action, parameters, callback) {
        // Perform any action here with the available data.
        // For example, you may want to use the new API or a relay server.
    }
});

Exclusions

These presets allow you to exclude items from the search results.

excludeAreas

An array of strings with default value []. Add options to the array to exclude those regions from search results. The valid options are:

ValueDescription
gbr_northern_irelandExcludes Northern Ireland from UK searches.
gbr_isle_of_manExcludes Isle of Man from UK searches.
gbr_isle_of_wightExcludes Isle of Wight from UK searches.
gbr_channel_islandsExcludes Channel Islands from UK searches.
gbr_all_except_northern_irelandExcludes all areas except Northern Ireland from UK searches. Only addresses in Northern Ireland will be returned.
usa_non_contiguousExcludes areas of the US that are not part of the 48 adjoining states: Alaska, American Samoa, Guam, Hawaii, Marshall Islands, Federated States of Micronesia, Northern Mariana Islands, Palau, Puerto Rico and Virgin Islands.
usa_insular_areasExcludes any US area that is not a state or federal district: American Samoa, Guam, Marshall Islands, Federated States of Micronesia, Northern Mariana Islands, Palau, Puerto Rico and Virgin Islands
usa_armed_forcesThis will exclude all Armed Forces Americas; Armed Forces Europe, Middle East, and Canada; and Armed Forces Pacific addresses.

Each option is prefixed with an ISO 3 country code. The exclusions for each option only apply while searching in this country. For example, gbr_channel_islands will exclude Jersey and Guernsey results while searching in the United Kingdom. It will not exclude Jersey results if Jersey is the selected search country.

excludePoBox

A boolean with default value false. This option will exclude any PO box addresses from the search results.

Advanced

relay

This string allows the user to override the URL to the server (for relay purposes).

Colors

The style object contains two keys, which can be used to set the main and secondary colors.

ParameterTypeValuesDefaultDescription
ambientstringlight, darklightSets the main color scheme for the search interface.
accentstringSee the list of possible colors below.defaultSets the secondary color for the search interface.

The following secondary colors are available:

ColorCodeColorCodeColorCode
default
red
pink
purple
deepPurple
indigo
blue
lightBlue
cyan
teal
green
lightGreen
lime
yellow
amber
orange
deepOrange
brown
grey
blueGrey

TIP

Colors and generic design come directly from Google’s Material UI. You can always apply custom colors or a unique design to the interface by forking and modifying our CSS file. This set of colors is mainly here to provide an instant theme for most websites.

Example of configuration using custom colors:

new clickToAddress({
    accessToken: 'xxxxx-xxxxx-xxxxx-xxxxx',
    dom: {
        search:     'search_field',
        line_1:     'addr_line1',
        line_2:     'addr_line2',
        company:    'addr_company',
        town:       'addr_town',
        postcode:   'addr_postcode',
        county:     'addr_county',
        country:    'addr_country'
        // Other available fields: latitude, longitude, post_office_reference_1
    },
    style: {
        ambient: 'dark', // Use black as main interface color
        accent: 'deepPurple' // Use deepPurple as secondary color for interface
    }
});

Texts

The 'texts’ object can be used to customize the text that is displayed as part of the search interface.

KeyTypeDefaultDescription
default_placeholderstringStart with post/zip code or streetPlaceholder to be displayed in the search box.
country_placeholderstringType here to search for a countryPlaceholder to be displayed when searching for a country in search box.
placeholder_country_overridesobject{}Object containing placeholders specific to a country. Object with ISO 3166 Alpha-3 (3 letter) country code as object keys, and a string for the placeholder.
country_name_overridesobject{}Object containing overrides for country names. Object with ISO 3166 Alpha-3 (3 letter) country code as object keys, and a string for the override name.
country_buttonstringChange CountryText to be displayed on button to change country in search interface.
generic_errorstringAn error occurred. Please enter your address manuallyText to be displayed when an error occurs.
no_resultsstringNo results foundText to be displayed when no results are found.
morestring moreText to be displayed when there are multiple sub-results, where displays the number of sub-results.

Example of configuration with custom texts:

new clickToAddress({
    accessToken: 'xxxxx-xxxxx-xxxxx-xxxxx',
    dom: {
        search:     'search_field',
        line_1:     'addr_line1',
        line_2:     'addr_line2',
        company:    'addr_company',
        town:       'addr_town',
        postcode:   'addr_postcode',
        county:     'addr_county',
        country:    'addr_country'
        // Other available fields: latitude, longitude, post_office_reference_1
    },
    texts: {
        // Placeholder to be displayed in the search box
        default_placeholder: 'Start with post/zip code or street',
        // Placeholder to be displayed when searching for a country in search box
        country_placeholder: 'Type here to search for a country',
        // Object containing placeholders specific to a country
        placeholder_country_overrides: {
            usa: "Enter ZIP code",
            gbr: "Enter postcode"
        },
        // Object containing overrides for default country names
        country_name_overrides: {
            usa: "America",
            gbr: "Great Britain",
        },
        // Text to be displayed on button to change country in search interface
        country_button: 'Change Country',
        // Text to be displayed when an error occurs
        generic_error: 'An error occurred. Please enter your address manually',
        // Text to be displayed when no results are found
        no_results: 'No results found'
        // Text to be displayed when there are multiple sub-results
        more: '{{value}} more'
    }
});

Functions

In many cases, it’s worth storing the result of the class initialization as a variable. Functions can be executed on this variable, such as the attach function.

.attach()

This function attaches the search functionality to a new set of elements. This allows the developer to initialize the class once, and then apply the search functionality to multiple forms on the same page. The attach function runs by default, if the configuration includes the dom object.

Attach accepts two parameters. The first is the DOM object for the new set of elements.

The second, optional parameter is also an object, and can be used to pass in config overrides for the new “instance” of the address search. Allowed configuration options for this method are:

  • onResultSelected
  • onSearchFocus
  • onSetCounty
  • disableAutoSearch

Basic example of attach - using first parameter only

cc = new clickToAddress(config);
cc.attach({
    search:     'search_field',
    town:       'addr_town',
    postcode:   'addr_postcode',
    county:     'addr_county',
    line_1:     'addr_line1'
});

Advanced example of attach - using both parameters

cc = new clickToAddress(config);
cc.attach({
    search:     'search_field',
    town:       'addr_town',
    postcode:   'addr_postcode',
    county:     'addr_county',
    line_1:     'addr_line1'
},
{
    onResultSelected: function(c2a, elements, address){
        // perform action here
    },
    onSetCounty: function(c2a, elements, address){
        // perform action here
    }
});

.selectCountry()

This method offers the ability to programmatically set the target country of the search. It takes a required string parameter - either an ISO 3166 Alpha-2 (2 letter) or Alpha-3 (3 letter) country code.

cc = new clickToAddress(config);
cc.selectCountry('AUS');

Error Messages

CodeMessage
JS500Unknown Server Error.
JS501API server seems unreachable.
JS502API search request resulted in a JS error.
JS503API address retrieve request resulted in a JS error.
JS505API countrylist retrieve request resulted in a JS error.
JS401Invalid value for countryMatchWith. Fallback to “text”.

WARNING

A special JavaScript variable called cc_debug is also initialized when the function is called. You can set this variable to true, which will result in all errors being reported directly to the developer console. cc_debug is not part of the clickToAddress object; it is a global variable. Its default value is false.