Having trouble with the search function in my array, as it is consistently returning false instead of the expected result

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:

  1. 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.
  2. If the entered zip code does not match any zip code in the array, it should state that the area is not serviced.
  3. 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:

  1. 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.
  2. If a zip code entered in the search bar does not exist in the array, it correctly says that the area is not serviced.
  3. 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>

Answer №1

The code snippet provided is attempting to locate the index of the string "search" instead of the variable search. The corrected version is as follows:

function searchResult(){ 
  var search = document.getElementById("search-box").value; 
  var index = zip.indexOf(search); // <--- using the variable instead of a string

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

Answer №2

The reason for the unusual result you're seeing is due to the utilization of indexOf with the string "search" rather than the variable search as outlined in the preceding line.

Answer №3

When looking for a specific string in your code, be sure to pass it as a variable instead of hardcoding it. Adjust the code like this:

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

Answer №4

To improve your code, make a change at this specific line: By making this adjustment, the code will dynamically search for the necessary zip instead of relying on the hardcoded zip value "search".

var index = zip.indexOf(search);

In the current code snippet below, it mistakenly attempts to locate the string "search" within the Zip array resulting in an index of -1 because "search" is not present as a distinct element.

var index = zip.indexOf("search");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve information from a text

I retrieved this data as a string from a webpage using jQuery and need help parsing it. When I attempted to use jQuery.parseJSON, I encountered the error Uncaught SyntaxError: Unexpected token n. The specific values I am looking for are "surl" and "imgur ...

Using jQuery to display items from GitHub API in a custom unordered list format

Attempting to access data from the GitHub API using jQuery (AJAX) and display it on a static webpage. Here are the HTML and JS code snippets: $(document).ready(function(){ $.ajax({ url: 'https://api.github.com/re ...

What is causing jQuery toggleClass to fail in removing a class?

I have successfully implemented a Skills accordion feature, but I am now trying to add a button that toggles all the skill sections at once. However, I am facing issues with jQuery not correctly adding or removing classes on the .accordion-trigger-all elem ...

What is the best way to iterate through states within an array using React?

Can someone help me create a button that can cycle through different states in the given array? I want the button to change State_1 to State_2, State_2 to State_3, and then back to State_1 for each object. I'm struggling to figure out how to cycle thr ...

Obtain geographic information using a JSON fetch from a map

I am facing an issue while integrating Laravel API data into React. Although I can see the JSON data in the console after fetching it, I encounter an error when I try to display it in a table for listing. The error states that my .map function is not recog ...

Image flipping effect malfunctioning in Safari and Internet Explorer

My image flipping effect is not functioning properly in Safari and IE browsers. Here is the code I am using: .flipcard { position: relative; width: 220px; height: 220px; perspective: 500px; margin: auto; text-align: center; } .flipcard.v:hove ...

Regular Expression to Replace Characters Not Matching

I am struggling with a coding issue that involves manipulating a string. The original string I have is "Hello This is world This". Here is the code snippet I have tried: var patt = 'Hello This is world This' var res = patt.constructor; alert( ...

When using Next JS with StoryBook, an error may occur if styles are written in a module.scss file

Every time I try to add some styles to my ButtonWidget.scss file, I encounter an error in the console when running the command yarn storybook Error Code: ERROR in ./src/components/ButtonWidget/ButtonWidget.module.scss 1:0 Module parse failed: Unexpected ...

Setting the default value for drop-down menus in jqGrid form editing

I have a data object with 3 attributes: ID Abbreviation Description In my jqGrid setup, I've configured the grid to display the Abbreviation. During editing (using the Form Edit feature), I populate the dropdown list with ID/Description pairs usin ...

Refresh stock value in anychart without having to re-render the entire chart

I am currently experimenting with the Anychart stock candlestick chart and I must say, it is quite impressive. However, I have encountered an issue while trying to update the chart using a setInterval function. The problem is that it re-plots the entire ch ...

Are there any jQuery plugins available that animate elements as the page is scrolled?

Looking for a library that can create entry animations for elements as the page is scrolled? I previously used the animate it library, which was great - lightweight and easy to use. However, it doesn't seem compatible with the latest jQuery version (3 ...

The URI entered is not valid: The parsing of the hostname failed. Electron Builder

Having an issue while trying to build an electron app using squirrel, even though the iconUrl is valid. Here is my package.json configuration: "squirrelWindows": { "iconUrl": "http://95.85.39.111:5005/skylog.ico" }, Error message received: An unhand ...

Create a div element that initially aligns to the left, expands to the full width of the window, and then shrinks back

Hi there! I am currently diving into the world of javascript and jQuery, with a specific goal in mind. I want to create functionality where a div expands to the width of the window when clicked, then shrinks back down to its original size but switches alig ...

What is the best method for retrieving a local value in Javascript?

Consider a scenario where there exists a variable named animationComplete (which is part of a 3rd-party library) and a function called happenAfterAnimation: An easy solution would involve the following code snippet: while(!animationComplete) { // Do n ...

What is the most effective method for invoking an inherited method (via 'props') in ReactJS?

From my understanding, there are two primary methods for calling an inherited method on ReactJS, but I am unsure which one to use or what the best practice is. class ParentCont extends React.Component { constructor(props) { super(props); t ...

bitcoinjs-lib for generating raw transactions in Node.js

var bitcoin = require('bitcoinjs-lib'); var rp = require('request-promise'); var data = Buffer.from('Hello World', 'utf8'); var testnet = bitcoin.networks.testnet; var privateKey = 'p2pkh'; var SourceAddre ...

Highcharts introduces shared tooltips for specific data series

I am seeking to implement specific behavior in highcharts regarding tooltips. The desired setup includes having two types of tooltips: the default shared tooltip a custom tooltip For the custom tooltip, a simple formatter can be utilized. However, the c ...

Update the object with fresh data once the XML data is transformed into JSON format

I am currently converting XML attributes into JSON format. Below is the complete function that I will explain step by step: request.execute('[someSP].[spSomeSP]', function(err, dataset) { if (err) { reject(err); } ...

I'm having trouble getting PHP/AJAX to return the expected XML data - it keeps

I have a JavaScript script that looks like this: function showItems(type) { var xmlhttp = new XMLHttpRequest(); //creating object var call = "getitems"; xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState ...

Using Jquery to make an Ajax request to an Asp.net Web Method

My current approach involves using a jquery method to transmit only the member identification # from the client side to the server side. On the server side, I have a traditional Web Method in place to receive the data and execute SQL queries accordingly. ...