0

I'm attempting to create a simple postcode search. I have been able to affect a change when the input value contains only the first two letter of each postcode, as defined in the variables.

var AB = "AB";
var AL = "AL";

However when a full postcode is entered, containing extra characters than the defined variables, no change is made. How do I need to structure the variables so they look for an input value that only contains the defined characters.

JSFiddle of what I have so far

Gary Voss
  • 225
  • 3
  • 13

1 Answers1

0

Multiple variables is redundant for what you're trying to do, use multi-dimensional array and loop through each. Solution on [jsFiddle here

$('.find').click(function() {

  var text = $("#distancePostcode").val().toLowerCase();
  var PostCode = {
    'AB': 'test1',
    'AL': 'test2'
  }

  for (var key in PostCode) {
    if (key.toLowerCase().indexOf(text) > -1) {
      for (var key2 in PostCode) {
        $('#' + PostCode[key2]).css("background", "");
      }
      $('#' + PostCode[key]).css("background", "red");
      break;
    }
  }

});
.test {
  margin: 10px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Postcode" id="distancePostcode"> <a class="find">find</a> 
<div class="test" id="test1">test 1</div>
<div class="test" id="test2">test 2</div>

]1

Diamond
  • 7,428
  • 22
  • 37