Verify the search input to see if the value matches in the array and display the corresponding response

As a beginner in Javascript, I have recently started learning the language in the past few weeks.

What I am looking for:

I want to create a search bar where users can enter their postcode and then the script will search through an array to find if the postcode is in any of the objects. It should then display the message found in the corresponding object.

I am able to get it to display the message, but only for the first postcode. I suspect that the issue lies within the loop.

var montering = {
  "postnummer": [{
    "id": "0",
    "codes": ["3089", "2089"],
    "msg": "Message 1"
  }, {
    "id": "1",
    "codes": ["3088", "2088"],
    "msg": "Message 2"
  }]
}



var placeholder = "";
document.getElementById('melding').innerHTML = placeholder;

//Script to search array for a match 
document.getElementById("searchBtn").addEventListener('click', function() {
  var formInput = document.getElementById("formInput").value,
    foundItem = null; //we'll store the matching value here

  if (formInput === '') {
    alert('Please enter a postcode');
    return false;
  }

  for (i = 0; i < montering.postnummer.length; i++) {
    if (montering.postnummer[i].codes[i] == formInput) {
      foundItem = montering.postnummer[i].codes[i];
      break; //we've found a match, no need to continue
    }
  }

  if (foundItem) {
    var msg = document.getElementById('melding');
    melding.innerHTML += 'Message: ' + montering.postnummer[i].msg;
  } else {
    alert("Code Number: '" + formInput + "' Was Not Found");
  }

});
<form method="get" action="input">
  <fieldset>
    <input id="formInput" name="formInput" type="text" placeholder="Enter your postcode" required/>
  </fieldset>
</form>

<input id="searchBtn" type="submit" value="Find price">
<p id="melding">Placeholder</p>

Answer №1

Utilize the Array.prototype.includes method on the codes array:

var montering = {
  "postnummer": [{
    "id": "0",
    "codes": ["3089", "2089"],
    "msg": "Message 1"
  }, {
    "id": "1",
    "codes": ["3088", "2088"],
    "msg": "Message 2"
  }]
}



var placeholder = "";
document.getElementById('melding').innerHTML = placeholder;

//Script to search array for a match 
document.getElementById("searchBtn").addEventListener('click', function() {
  var formInput = document.getElementById("formInput").value,
    foundItem = null; //we'll store the matching value here

  if (formInput === '') {
    alert('Enter a postal code');
    return false;
  }

  for (i = 0; i < montering.postnummer.length; i++) {
    if (montering.postnummer[i].codes.includes(formInput)) {   // modify this line
      foundItem = montering.postnummer[i].codes[i];
      break; //we've found a match, no need to continue
    }
  }

  if (foundItem) {
    var msg = document.getElementById('melding');
    melding.innerHTML += 'Message: ' + montering.postnummer[i].msg;
  } else {
    alert("Code Number: '" + formInput + "' Was Not Found");
  }

});
<form method="get" action="input">
  <fieldset>
    <input id="formInput" name="formInput" type="text" placeholder="Enter your postal code" required/>
  </fieldset>
</form>

<input id="searchBtn" type="submit" value="Find price">
<p id="melding">Placeholder</p>

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

Puppeteer will not navigate to chrome://version when running in headless mode

Currently, I am utilizing the puppeteer.connect method to navigate to chrome://version in order to extract the user-agent being used by Puppeteer. Everything works fine when headless mode is disabled, but an error occurs when attempting it with headless mo ...

What is the method for striking through a line in a table?

I developed a unique jQuery script: <script type="text/javascript"> $(document).ready(function () { $('tr.inactive').each(function (index) { var tr = $(this); tr.find('td:first').after(function ...

Record changes in another sheet when Google Spreadsheet is edited

Can anyone provide assistance with a problem in Google Spreadsheet? I am looking to log the name and timestamp when a value in a specific column in the "Venues" sheet is changed. However, I'm having trouble determining if I'm working with the co ...

Storing Data in an Array Using MongoDB's $push Method Depending on a Variable's Value

I'm attempting to add an item to my MongoDB record in Node (using MongoJS) by using the $push method. Here is an example of how it's done: exports.saveToUser = function (req, res) { console.log("IN"); var user = req.params.user; var ...

What is the correct way to initialize a variable that will store the output of setInterval?

While examining a question, I came across someone's solution that proposed updating the code below. In the comments section, it was suggested: Instead of setting this.tm to undefined, we should set it to 0. Since it's a time interval, it shoul ...

Hosting files for a URL with dynamic parameters in Node.js can be achieved without relying on any external libraries or frameworks

I'm dealing with a minor issue. I'm trying to serve a static file for the "/user/:id" URL using a simple node server. Can someone guide me on how to achieve this? On the client side, I have the following request: document.location.href = `http:/ ...

How can I initiate a TextChange event in ASP.NET C# without losing focus?

I attempted to trigger the TextChange event using Ajax, but it doesn't seem to be working as I expected. I'm hoping someone here can lend a hand. <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> ...

Using Node.js, securely encode data using a private key into a base64 format that can only be decoded on the server side

Here is my specific situation: An http request arrives at the server for a login action A user token needs to be created. This token consists of a Json object composed of different fields. It is then converted to a string and encoded in Base64. const ...

What is the most effective way to display a card with varying values depending on the user's input in a form?

For a while now, I've been grappling with a particular challenge. In my project, I am utilizing multiple states to display values within a card after they are entered into a form. The first state captures the values and modifies the initial state, whi ...

The button should only be visible when the input is selected, but it should vanish when a different button within the form is

Having an issue with displaying a button when an input field is in focus. The "Cancel" button should appear when a user interacts with a search bar. I initially used addEventListener for input click/focus to achieve this, but ran into a problem: on mobile ...

Having trouble with a 'Could not find a declaration file for module' error while using my JavaScript npm package?

I recently released a JavaScript npm package that is functioning properly. However, when importing it into another application, there always seems to be three dots in front of the name, along with an error message that reads: Could not find a declaration f ...

Incorporating a new function into a TypeScript (JavaScript) class method

Is it possible to add a method to a method within a class? class MyClass { public foo(text: string): string { return text + ' FOO!' } // Looking for a way to dynamically add the method `bar` to `foo`. } const obj = new MyCl ...

Determine whether the array is in ascending order

My Java array int[] field = new int[9] has the following elements: {1,2,3,4,5,6,7,8,9,0} In the method public static boolean isSorted(int[] field, boolean isAscending), I aim to determine whether the array is in ascending or descending order. My initial a ...

Troubles with the compatibility of javascript and jquery's multiselect plugin

I've been utilizing the multiselect API to create a dropdown with multiple select options. This is my HTML code: <select id="options" multiple="multiple"></select> And this is my JS code: render:function(){ // $('#viewTemp& ...

Every time a GET request is made to the same route in Express.js, it seems to be stuck in a

Currently, I am working on an express application that requires a landing page to be rendered for the '/' route. This landing page consists of a text box and a submit button. The desired functionality is such that when a user enters some text int ...

I am seeking to enable a specific div when the crawler condition is met

This specific div houses the character and becomes active when the character is clicked. Upon clicking, a jQuery function is triggered to display other countries. //this particular div should remain active when the crawler condition is met. It displays th ...

What are the steps to integrate HJSON with Jest in a create-react-app development environment?

Currently, I am utilizing HJSON within a create-react-app project (view answer here). However, Jest does not utilize the same webpack configuration, resulting in a failed import of HJSON - for instance, import options from '../assets/options.hjson&ap ...

Vue - making one element's width match another element's width

Trying to dynamically adjust the innermost element's width to match the outermost element's width with Vue: <div id="banner-container" class="row"> <div class="col-xs-12"> <div class="card mb-2"> <div ...

Understanding the Functioning of a Digital Analog Clock Using JavaScript

As a new learner, I found the operation of a Digital analog clock to be quite puzzling. I was presented with an image called clock.png, and I specifically struggled with how the hands of the clock function. Javascript - const deg = 6; // defining the valu ...

JavaScript form submission failing to transmit updated data

I have been working on a JavaScript function that changes the hidden value of a form based on which button is clicked, and then sends it via post to a processing page. Even though I have confirmed that the value is being changed correctly, when the post i ...