Ryan Perez
Ryan Perez

Reputation: 139

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;
}

Upvotes: 1

Views: 76

Answers (2)

Matt U
Matt U

Reputation: 5118

checkIfAvailable can use find to return the inner array, if present:

function checkIfAvailable(zip) {
    let zones = [...];
    // Find an inner array where the first element [0]
    // is the zip
    return zones.find(item => item[0] === zip);
}

Then in validateZip:

const zone = checkIfAvailable(zip);
if (zone) {
    // zone will be the matching inner array
    // such as ["90210", "Beverly Hills"]
    const State = zone[1];
    msg = "Our service is available in " + State;
}

Upvotes: 1

caramba
caramba

Reputation: 22490

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>

Upvotes: 1

Related Questions