Posted on Leave a comment

How to create a basic postcode lookup or address finder field using easy-autocomplete

There are many ways you could make a REST call to our services and there are tons of libraries in many languages that facilitate this.

On the home page of Addressian, there is a demo section that implements “search-as-you-type” and “postcode-lookup” style address finders. Here is how they are implemented:

We use a Javascript library called easy-autocomplete.

Add the dependencies to your HTML page’s header section:

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/jquery.easy-autocomplete.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/easy-autocomplete.min.css">

Search-as-you-type

First create a section in your HTML form with an “input” element inside it:

<section class="easy-autocomplete">
  <div>
  <input id="tags" type="text" autocomplete="off" placeholder="Search...">
  </div>
 </section>

Then add this bit of Javascript, anywhere in your HTML source code:

<script>
  $(function() {
   var selectItem = function(event, ui) {
    $("#tags").val(ui.item.value);
    return false;
   }
   var options = {
    url: function(phrase) {
     return "https://api-trial.addressian.co.uk/address/" + phrase;
    },
    ajaxSettings: {
     headers: {
      'x-api-key': '[your_api_key]'
     }
    },
    getValue: function(element) {
     return element;
    },
    theme: "blue-light",
    placeholder: "Type an address in here..",
    list: {maxNumberOfElements: 20}
   };
   $("#tags").easyAutocomplete(options);
  });
 </script>

Retrieve addresses from a postcode

First create a section in your HTML form with an “input” element inside it:

<section class="easy-autocomplete">
  <input id="postcode" type="text" autocomplete="off" placeholder="search...">
  <button id="postcode-go">Go</button>
  <select id="postcode-dropdown" hidden=""></select>
 </section>

Then add this bit of Javascript, anywhere in your HTML source code:

<script>
  jQuery("#postcode-go").click(function() {

   if (jQuery("#postcode").val() == '') {
    return;
   }
   let dropdown = jQuery('#postcode-dropdown');
   dropdown.empty();
   dropdown.show()
   dropdown.append('<option selected="true" disabled>Choose your address</option>');
   dropdown.prop('selectedIndex', 0);
   const url = '';
   jQuery.ajax({
    beforeSend: function(request) {
     request.setRequestHeader("x-api-key", '[your_api_key]');
    },
    dataType: "json",
    url: "https://api-trial.addressian.co.uk/address/" + jQuery("#postcode").val(),
    success: function(data) {
     jQuery.each(data, function(key, entry) {
      dropdown.append(jQuery('<option></option>').text(entry.address.join(', '));
     })
    }
   });
   jQuery.getJSON("", function(data) {});
  });
 </script>

Leave a Reply