首页 > 解决方案 > 找到邮政编码时验证邮政编码和打印状态

问题描述

此应用程序的主要目标是提供邮政编码搜索,然后在找到邮政编码后显示与邮政编码相关联的状态。如何修改此代码以反映我想要实现的目标?

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

标签: javascriptzipcode

解决方案


如果您可以将其更改array为 an object,那么它将非常简单:

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>


推荐阅读