Postcode Lookup & Address Search
The jQuery plugin is the fastest way to integrate Postcode Lookups on a web page. To see working examples, visit our jQuery Demo page, or try our Postcode Lookup demo.
Initialisation
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 dropdown 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.
$('#postcode_lookup_field').setupPostcodeLookup({
api_key: 'api_key',
output_fields: {
line_1: '#first_line',
line_2: '#second_line',
line_3: '#third_line',
post_town: '#post_town',
postcode: '#postcode'
}
});
Interface
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
Tested against jQuery 1.9, 1.10, 1.11, 2.0, 2.1, 2.2, 3.0, 3.1 and 3.2
Latest Build
Current version is 3.0.*. This documentation is applicable to the latest version only.
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 calledonSearchCompleted
- Removed client side postcode validation
The documentation for version 2.2.4 can be found here
Getting Started
Download the plugin and add to your page with <script src="postcodes.min.js"></script>
Sign up to get an API key
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)
$('#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'
}
});
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 address 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
"country" : "", // Country
"ward" : "", // Ward
"uprn" : "" // Unique Property Reference Number
}
More information on what these fields mean can be found in PAF documentation page.
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.licensee |
string |
Optional licensee key |
options.tags |
string[] |
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.licensee |
string |
Optional licensee key |
options.limit |
number |
Maximum number of matches to return (default is 10, maximum is 100) |
options.tags |
string[] |
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()
.
Property | Type | Default | Description |
---|---|---|---|
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:
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 |
tags |
string[] |
undefined |
Label your requests using |
licensee |
string |
null |
Optional licensee key (for sublicensed key usage) |
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_ |
string |
"We could not find a match for your address. Please type in your address" | The default error message following a failed address lookup. i.e. when plugin is configured with `address_search: true` |
error_message_ |
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 when 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. |
onDropdownDestroyed |
function |
undefined |
A function invoked when dropdown is removed from the DOM as user attempts to search another address or postcode. |
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. |
shouldLookupTrigger |
function |
undefined |
A function invoked just before the plugin triggers a lookup when the search button is clicked. This property
takes a function, which accepts a done function as its first argument.Invoke done to allow the plugin to continue to make a HTTP request against the Ideal Postcodes
API.done may also be invoked asynchronously, however be aware that the DOM or plugin state
may have mutated should there be a long pause between the search action and invoking done . |