Documentation

jQuery Plugin Build Status npm version

The jQuery plugin is the fastest way to integrate postcode lookups on a web page. To see working examples, visit our jQuery Demo page.

This plugin generates an input field to receive postcode inputs from the user and a button to run address lookups via the Ideal Postcodes API. If a matching postcode is found, a drop down menu is created and the selected address is piped into the form. If no matching postcode is found or an error occurred, the plugin will append an appropriate message.

The plugin provides addresses according to Royal Mail's Addressing Guidelines. This consists of 3 address lines, a Post Town and Postcode and is sufficient to uniquely identify a premise in the UK.


Build Info

Latest : Github, NPM

Tested against jQuery 1.9, 1.10, 1.11, 2.0 and 2.1.

Sauce Test Status


Latest Changelog

Version 3.0.0 brings some backwards incompatible changes

  • Reformed postcode, address search and key checking APIs
  • Request tagging
  • Custom error message container
  • More appropriately named custom callbacks
  • onLookupSuccess is now called onSearchCompleted
  • Removed client side postcode validation

The documentation for version 2.2.4 can be found here


Getting Started

1) Download the plugin and add to your page

<script src="jquery.postcodes.min.js"></script>

2) Sign up to get an API key

3) Setup a Postcode Search Field by inserting an empty div tag and calling .setupPostcodeLookup(). Pass in a configuration object identifying your API Key and address fields (via CSS selectors)

<div id="postcode_lookup_field"></div>
<script>
$('#postcode_lookup_field').setupPostcodeLookup({
    api_key: 'your_key_goes_here',
    // Pass in CSS selectors pointing to your input fields
    output_fields: {
        line_1: '#first_line',
        line_2: '#second_line',
        line_3: '#third_line',
        post_town: '#post_town',
        postcode: '#postcode'
    }
});
</script>

Available Addressing Data

By rigging just 5 fields in the above example, you will have the necessary information you need (and in the correct formatting) to identify any household in the UK by mail.

However, you can extract more information on each address for your addresss form by passing more properties into the output_fields object.

Here's the complete list of available data fields:

"output_fields": {
    "line_1": "",                      // Address Line 1 
    "line_2": "",                      // Address Line 2
    "line_3": "",                      // Address Line 3
    "post_town": "",                   // Post Town
    "postcode": "",                    // Postcode
    "premise": "",                     // Premise Name
    "udprn" : "",                      // Unique Delivery Point Reference Number
    "organisation_name" : "",          // Organisation Name
    "department_name" : "",            // Department Name
    "po_box" : "",                     // PO Box Number
    "postcode_inward" : "",            // Postcode Inward Code
    "postcode_outward" : "",           // Postcode Outward Code
    "building_number" : "",            // Building Number
    "building_name" : "",              // Building Name
    "sub_building_name" : "",          // Sub Building Name
    "thoroughfare" : "",               // Thoroughfare
    "dependant_thoroughfare" : "",     // Dependant Thoroughfare
    "dependant_locality" : "",         // Dependant Locality
    "double_dependant_locality" : "",  // Double Dependant Locality
    "postcode_type" : "",              // Postcode Type
    "su_organisation_indicator" : "",  // Organisation Type
    "delivery_point_suffix" : "",      // Delivery Point Suffix
    "longitude" : "",                  // Longitude
    "latitude" : "",                   // Latitude
    "northings" : "",                  // Northings
    "eastings" : "",                   // Eastings
    "county" : "",                     // Aggregated County Field
    "postal_county" : "",              // Postal County
    "administrative_county" : "",      // Administrative County
    "traditional_county" : "",         // Traditional County
    "district" : "",                   // District
    "ward" : ""                        // Ward
}

More information on what these fields mean can be found here

To add them into your form, simply include it in output_fields when initialising Ideal Postcodes. The example below demonstrates how the organisation name can be routed to the input with the id "organisation_field"

<script>
$("#myLookupField").setupPostcodeLookup({
    api_key: 'iddqd',
    output_fields: {
        line_1: '#first_line',
        line_2: '#second_line',
        line_3: '#third_line',
        post_town: '#post_town',
        postcode: '#postcode',
        organisation_name: '#organisation_field'
    }
});
</script>

Plugin Configuration Examples

The plugin may also be configured for closer integration on a form. Below is a non-exhaustive list of what may be done:

Pipe additional addressing data to your form like organisation name, county or geolocation

Style input elements generated by the plugin with CSS classes

Provide your own customised input or button elements

Add multiple more than one postcode lookup fields on a page

Handle cases where your key cannot be used. E.g. No balance or limit reached.


Other Methods

This plugin also exposes a couple of methods which you may find useful without having to invoke the plugin. These methods are listed below


$.idealPostcodes.lookupPostcode(options, callback)

Retrieve all addresses at a given postcode

Function Arguments

Argument Type Description
options Object A configuration object for postcode lookups. Configurable attributes listed below
options.postcode String The postcode to lookup (case insensitive)
options.api_key String API Key to access service
options.tags Array Label your requests using tags, which can be queried later. Accepts an array of strings. E.g. ["CRM"]
callback Function Asynchronous handler when data addresses are received. This function accepts 2 arguments. The first is error, which will be null for successful requests. Errors will surface if your key has no balance or one or your predefined limits has been reached. The second argument is addresses, which is an array of address objects matching your query. Invalid postcodes will return an empty array.

Example


var API_KEY = 'iddqd';

$.idealPostcodes.lookupPostcode({ 
    postcode: 'ID11QD', 
    api_key: API_KEY 
}, function (error, addresses) {
    if (error) {
        // Handle error
    }
    console.log(addresses[0]); 
    // prints to console: 
    // {  
    //      postcode: "ID1 1QD", 
    //      post_town: "LONDON", 
    //      line_1: "Kingsley Hall", 
    //      line_2: "Powis Road", 
    //      line_3: ""
    //      ...truncated...
    //  } 
});


$.idealPostcodes.lookupAddress(options, callback)

Performs an address search on the Ideal Postcodes API using a search string

Function Arguments

Argument Type Description
options Object A configuration object for address search. Configurable attributes listed below
options.query String The address query string to search for
options.api_key String API Key to access service
options.limit Number Maximum number of matches to return (default is 10, maximum is 150)
options.tags Array Label your requests using tags, which can be queried later. Accepts an array of strings. E.g. ["CRM"]
callback Function Asynchronous handler when data addresses are received. This function accepts 2 arguments. The first is error, which will be null for successful requests. Errors will surface if your key has no balance or one or your predefined limits has been reached. The second argument is addresses, which is an array of address objects matching your query. Invalid postcodes will return an empty array.

Example


var API_KEY = 'iddqd';

$.idealPostcodes.lookupAddress({ 
    postcode: '10 Downing Street London', 
    api_key: API_KEY 
}, function (error, addresses) {
    if (error) {
        // Handle error
    }
    console.log(addresses[0]); 
    // prints to console: 
    // {  
    //      postcode: "SW1A 2AA", 
    //      post_town: "LONDON", 
    //      line_1: "Prime Minister & First Lord Of The Treasury", 
    //      line_2: "10 Downing Street", 
    //      line_3: ""
    //      ...truncated...
    //  } 
});



Available jQuery Configuration Options

Below is a list of optional parameters you can use to style or modify the postcode lookup elements generated by the plugin. Pass this in your configuration object when calling .setupPostcodeLookup().

PropertyTypeDefaultDescription
debug_mode Boolean false When set to true, any errors will display the error messages and response code
disable_interval Number 1000 Sets a short time period (in ms) after a lookup in which the lookup button is disabled
remove_organisation Boolean false Removes the organisation name from the address lines (line_1, line_2, line_3). When an organisation is registered at an address, clear addressing guidelines dictate that the organisation name must be at the head of the address (line_1). Switching this flag to true will remove the organisation name.
check_key Boolean false

If enabled, the plugin will check if the key is in a usable state before initialising itself.

The check can fail if:

  • Your key has no remaining lookups
  • Your key has run into its lookup limit for the day
  • Your key is requested from a URL which is not on your whitelist
  • The user seeking to use the key has exceeded their limit for the day

If the check fails, the plugin will not initialise. You can use the callbacks provided to customise your response to a successful or unsuccessful key check.

address_search Boolean or Object false

If enabled, any lookups which do not validate as a standard postcode will be passed to the address search API instead.

You can configure address search by passing in an Object. Currently this configuration object only accepts one parameter: limit. Limit determines the maximum number of search results to return. (Default is 10, maximum is 150)

tags Array undefined

Label your requests using tags, which can be queried later. Accepts an array of strings. E.g. ["CRM"]

Input Field. Modifies the postcode input field
input_class String "" Sets the class of the input field
input_label String "Please enter your postcode" Sets the embedded label
input String undefined If you wish to use your own input field, you can specify the unique css selector for that field here. E.g. "#myCustomPostcodeLookupField". Please note that all input field parameters like input_class and input_label will be ignored. It will be up to you to implement styling and any desired behaviours in your input field.
Lookup Button. Modifies the lookup button
button_class String "" Sets the class of the lookup button
button_label String "Find my Address" Sets the label on the button
button_disabled_message String "Looking up postcode..." Sets label of the button when it is temporarily disabled (during a lookup)
button String undefined If you wish to use your own lookup button, you can specify the unique css selector for that field here. E.g. "#customLookupTrigger". Any "clickable" DOM element will work as a valid "button" to trigger a lookup. Please note that all other parameters like button_disabled_message will be ignored. It will be up to you to implement styling and any desired behaviours for your lookup button.
Dropdown Menu. Modifies the address selection menu (a select element)
dropdown_class String "" Sets the class of the dropdown select menu
dropdown_select_message String "Please select your address" Sets the topline message for the dropdown menu
dropdown_container String undefined Specify a custom container for the dropdown menu using a CSS selector
Error Messages. The error message in various invalid states
error_message_class String "" Sets the class of the error message p element
error_message_default String "Sorry, we weren't able to get the address you were looking for. Please type your address manually" The default error message following a failed postcode lookup.
error_message_
invalid_postcode
String "Please check your postcode, it seems to be incorrect" The error message following a postcode which does not pass a basic regex test
error_message_not_found String "Your postcode could not be found. Please type in your address" The error message following a postcode lookup in which the postcode does not exist
error_message_container String undefined Specify a custom container for the error message container menu using a CSS selector. If an error prompt needs to be shown (e.g. postcode not found) a <p> tag containing the message is inserted into the specified container.
Callbacks. You may also specify functions that will be invoked at various stages of making a postcode lookup
onLoaded function undefined A function invoked once the plugin has initialised.
If the plugin is configured to check the key, i.e. check_key: true, this callback will only be invoked if the key is usable.
onFailedCheck function undefined A function invoked if check_key is enabled and the check fails.
onSearchCompleted function undefined A function invoked when a successful API request is made. An API request is made
Note that this is also invoked on 400-type errors such as "postcode not found" or "lookup balance exhausted". This property takes a function, which accepts a `data` argument representing the raw JSON response.
onAddressesReceived function undefined A function invoked when a successful API request is made and at least 1 address is returned. This property takes a function, which accepts an `addresses` argument representing the addresses returned by the API.
onAddressSelected function undefined A function invoked when the user selects an address option on the plugin's dropdown menu. This property takes a function, which accepts a address argument representing the full details of the selected address. this is bound to the selected DOM element.
onDropdownCreated function undefined A function invoked addresses have been retrieved and the dropdown has been inserted into the DOM. This property takes a function, which accepts a $dropdown argument representing the jQuery wrapped dropdown element.
onLookupTriggered function undefined A function invoked when the user triggers a lookup (e.g. by clicking the button). This callback is invoked before any request is made to the API.
onSearchError function undefined A function invoked when the API returns an error. This property takes a function, which accepts an error argument representing the error returned by the API.
Examples of errors includes "lookup balance exhausted" and "lookup limit reached" errors.