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


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.


Advanced Usage


$.idealPostcodes.lookupPostcode(postcode, api_key, success[, error])

Performs a postcode lookup on the Ideal Postcodes API

Function Arguments

Argument Type Description
postcode String The postcode to lookup (case insensitive)
api_key String API Key to access service
success Function Asynchronous handler when data is received. If data.code != 2000, an error has occured
error Function (Optional) Asynchronous handler in case of request timeout

Example


var API_KEY = 'iddqd';

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



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)

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
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, this callback will only be invoked if the key is usable.
onFailedCheck function undefined If the plugin is configured to check the key, this callback will only be invoked if the key is not usable.
onLookupSuccess function undefined A function invoked when a successful 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 JSON response.
onLookupError function undefined A function invoked when the plugin was not able to make a successful request to the API. For instance, a request timeout. This property takes a function with no arguments.
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.