Skip to content Skip to sidebar Skip to footer

Check If Zip Code In Input Exists In JSON And Get Category

I have a JSON element with a bunch of different zip codes associated with 'zones.' What I would like to do is allow a user to submit their zip code, check if the zip code exists wi

Solution 1:

You can use Array.find

var zones = [
  {
		"zone": "one",
		"zipcodes": ["69122", "69125", "69128","69129"]
	},
	{
		"zone": "two",
		"zipcodes": ["67515", "67516", "67518", "67521"]
	}
];

$(function() {
  $('#userZip').submit(function(e) {
    e.preventDefault();
    var userZip = $('input[type="text"]').val();
    // find the first zone with the userZip inside its zipcodes list
    var zone = zones.find(function(zone) {
      return zone.zipcodes.indexOf(userZip) > -1;
    });
    alert("Zone: " + zone.zone);
  });
});
i {
  display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="userZip">
  <i>Enter zip code "69122" as an example</i>
  <input type="text" placeholder="zip" />
  <input type="submit" />
</form>

Post a Comment for "Check If Zip Code In Input Exists In JSON And Get Category"