0

I have an EasyAutocomplete input field that takes in a UK postcode which is retrieved by the postcodes.io API. I am using the autocomplete function (api.postcodes.io/postcodes/{input}/autocomplete) which returns a list of possible matches for the given input in the following format.

Input: "a"

Output:

{
    "status": 200,
    "result": [
        "AB10 1AB",
        "AB10 1AF",
        "AB10 1AG",
        "AB10 1AH",
        "AB10 1AL",
        "AB10 1AN",
        "AB10 1AP",
        "AB10 1AQ",
        "AB10 1AR",
        "AB10 1AS"
    ]
}

However when there is no postcode matched, the result returns null (note that the status remains at 200).

Input: "asdasdasdasdas"

Output:

{
    "status": 200,
    "result": null
}

The code I wrote can retrieve the postcodes successfully, but when I type something that doesn't match any postcode, EasyAutocomplete throws an error and renders the input field unusable unless the page is refreshed. I'm trying to find a way to detect if the result is null before EasyAutocomplete executes.

JavaScript:

function postcodeLookup() {
    var options = {
        url: function(phrase) {
            if (phrase !== "") {
                phrase.replace(/\s/g, "");
                return "https://api.postcodes.io/postcodes/" + phrase + "/autocomplete";
            }
        },

        ajaxSettings: {
            dataType: "json"
        },

        listLocation: "result",

        requestDelay: 300
    };

    return options;
}

$("#p-pc").easyAutocomplete(postcodeLookup());

Input field:

<input id="p-pc" placeholder="Postcode" maxlength="10" name="pc"/>
Flik
  • 365
  • 1
  • 7
  • 18

1 Answers1

0

Without making a request , you cannot know ahead of time if you will get an empty or non-empty array. Perhaps add easyAutoComplete as well(where you actually make a request).

Ankush Verma
  • 689
  • 1
  • 8
  • 17