Aim: I am working on creating a basic search bar that allows users to input a zip code and matches it with zip codes stored in an array. The objective is to develop a function that can determine whether the entered zip code exists in the array or not, and provide corresponding output statements based on the result.
Desired Outcome:
- If the zip code entered in the search bar matches any zip code in the array, it should display a message indicating that the area is serviced.
- If the entered zip code does not match any zip code in the array, it should state that the area is not serviced.
- In case of a submission with a blank input field, a prompt should appear asking the user to enter a valid zip code.
Current Outcome:
- If a zip code entered in the search bar matches a zip code in the array, the output mistakenly states that the area is not serviced.
- If a zip code entered in the search bar does not exist in the array, it correctly says that the area is not serviced.
- Submitting a blank input field triggers a validation message instructing the user to enter a valid zip code.
Code Snippet:
var zip = ["19505", "19506", "19507", "19508", "19510", "19511", "19512", "19518","19519", "19522", "19523", "19526", "18056", "19529", "19530", "19533", "19534", "19535", "19536", "19538", "19539", "19540", "19541", "19542", "19543", "19544", "19545", "19547", "19611", "19601", "19602", "19604", "19605", "19606", "19607", "19608", "19550", "19551", "19554", "19555","19559","19560","19562", "19564", "19565","19609", "19567", "19610"];
function validateSearchbox(){
var input = document.getElementById("search-box")
if(input.value.length > 0){
searchResult();
} else {
document.getElementById("search-result").innerHTML = "Please enter a zip code";
}
};
function searchResult(){
var search = document.getElementById("search-box").value;
var index = zip.indexOf("search");
if(index !== -1){
document.getElementById("search-result").innerHTML = "Yes, we do service your area!";
} else {
document.getElementById("search-result").innerHTML = "Sorry, we do not service your area!";
}
};
<div id="search">
<input type ="search" id="search-box" placeholder="Zip Code" maxlength="5"/>
<button onClick="validateSearchbox();" id="search-btn"> Search </button>
</div>
<p id="search-result" style="font-size: 30px; font-weight: 500px;"> </p>