Search code examples
javascriptzipcode

Validate Zipcode and Print State when Zipcode is found


The primary objective of this application is to provide a search of a zipcode, followed by the display of the state associated with the zipcode once the zipcode has been located. How can I modify this code to reflect what it is that I am trying to acheive?

    <input type="text" id="zipCode" placeholder="ZIP code" onKeyUp="validateZip()"/>
<div id="msg"></div>

    function checkIfAvailable(zip)
{
  let zones = [["90210","Beverly Hills"],
              ["90211","BH"]]
  return( zones.indexOf(zip) >= 0 )
}

function validateZip()
{
  let zip = document.getElementById("zipCode").value;
  let msg =""
  if(checkIfAvailable(zip)
    {
      msg="Our service is available in" + State
     ;
    }
   else
     {
       msg="Sorry our service is not available in this area";
     }
    document.getElementById("msg").innerHTML = msg;
}

Solution

  • if you can change the array to an object it would be as simple as:

    let zones = {90210: "Beverly Hills", 90211:"BH"};
    let msgElement = document.getElementById("msg")
    
    function validateZip(userInput) {
      if (userInput.value in zones) {
         msgElement.innerHTML = "Our service is available in " + zones[userInput.value];
      } else {
        msgElement.innerHTML = "Sorry our service is not available in this area";
      }
    }
    <input type="text" id="zipCode" placeholder="ZIP code" onKeyUp="validateZip(this)"/>
    <div id="msg"></div>