0

I need a small form to check the first half of UK postcode. Ive added the first half of the postcodes in an array.

The form has a simple input field and submit button. When the user types in first half of a postcode for example N1 I want the form to check the array, if there is match, I want a div to fade in displaying a message.

    <form class="navbar-form navbar-left" role="search" id="searchForm">
<div class="form-group">
<input type="text" name="s" class="form-control covered-area-search-input" placeholder="Enter the first half of your postcode...">
</div>
<button type="submit" class="btn btn-default" value="Search"><i class="fa fa-paper-plane"></i> Submit</button> 
</form>

<div id="result"></div>

jQuery:

var postcodes = ["N1", "N2", "N3", "N4", "N5", "N6", "N7", "N8", "N9", "N10", "N11", "N12", "N13", "N14", "N15", "N16", "N17", "N18", "N19", "N20", "N21", "N22", "NW1", "NW2", "NW3", "NW4", "NW5", "NW6", "NW7", "NW8", "NW9", "NW10", "NW11", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "E10", "E11", "E12", "E13", "E14", "E15", "E16", "E17", "E18", "W1", "W2", "W3", "W4", "W5", "W6", "W7", "W8", "W9", "W10", "W11", "W12", "W13", "W14"];

$('#search').submit(function(){
        var postcode = $('#search input').val();  
        if($.inArray(postcode.toUpperCase(), postcodes ) > -1){
            $('#result').html('Yes, we cover your area!');
        }else{
            $('#result').html('Oops, it looks like we do not cover that area yet.');
        }

        return false;
    });

I tried the above code but no luck. How would I do this? Many thanks in advance.

Sami
  • 1
  • 1
  • 5

1 Answers1

1

There is no form with id 'search'; it is 'searchForm'. Can you update your jQuery like below;

$('#searchForm').submit(function(){
    var postcode = $('#searchForm input').val();  
    if($.inArray(postcode.toUpperCase(), postcodes ) > -1){
        $('#result').html('Yes, we cover your area!');
    }else{
        $('#result').html('Oops, it looks like we do not cover that area yet.');
    }

    return false;
});
Yepo
  • 134
  • 4
  • Thanks, that fixed the issue. :) not sure why I used search instead of searchForm. – Sami Feb 19 '17 at 22:31
  • Any suggestions on how I can convert this code for a partial match? eg. if someone typed in E1 4AB, it will still return true as the first half of the postcode is in the array. – MV-123 Jan 29 '18 at 16:44