Is the input in the array? How to find out?

I am currently facing an issue with a script that I have created to count array elements matching a user input. Strangely, all if statements in the script seem to be returning false.

I have verified that both the array element and the input value are strings, so I can't seem to pinpoint why this problem is occurring.

<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>
      <div>
        <input type="text" id="searchType">
      </div>
      <p id="count"></p>

      <script type="text/javascript">

      var bloodTypes = ["A+", "O-", "AB+", "O+", "AB+", "AB+", "O-", "AB+", "0+", "AB+"];
      var n = 0;

      for (var i = 0; i < bloodTypes.length; i++) {
         if (bloodTypes[i] == document.getElementById("searchType").value){
            n++;
         }
      }
      document.getElementById("count").innerHTML = n;
      </script>
   </body>
</html>

Answer №1

const bloodCollection = ["A+", "O-", "AB+", "O+", "AB+", "AB+", "O-", "AB+", "0+", "AB+"];
const searchCriteria = document.getElementById("searchType");
const resultCounter = document.getElementById("count");

searchCriteria.addEventListener('input', function (event) {
    let count = 0;
    for (let index = 0; index < bloodCollection.length; index++) {
        if (bloodCollection[index] == event.target.value) {
            count++;
        }
    }
    resultCounter.textContent = count;
});

Answer №2

You currently face three challenges.

  1. At the moment, your code begins running immediately upon page load, even before the user has a chance to input a search string.
  2. Your counting logic needs to be encapsulated within a callable unit of code (a function) so that it can execute at the appropriate time.
  3. A "trigger" or event must be established for the count code to activate. In this case, it's set up with the change event, which triggers after the input value changes and focus on the control is lost (by hitting TAB).

Refer to the comments included below for further clarification:

<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>
      <div>
        <input type="text" id="searchType">(hit TAB after entering data)
      </div>
      <p id="count"></p>

      <script type="text/javascript">
      
      // The prior code was assessing matches before any user input was made. An "event handler" needs to be implemented to run the code at the correct time:
      document.getElementById("searchType").addEventListener("change", count);

      // Consolidate all script within a function to be initiated after search input
      function count(){
        var bloodTypes = ["A+", "O-", "AB+", "O+", "AB+", "AB+", "O-", "AB+", "0+", "AB+"];
        var n = 0;

        for (var i = 0; i < bloodTypes.length; i++) {
         if (bloodTypes[i] == document.getElementById("searchType").value){
            n++;
         }
        }
        
        // Use .textContent instead of .innerHTML when working with non-HTML strings
        document.getElementById("count").textContent = n;
      }
      </script>
   </body>
</html>

This process can be simplified using the Array.forEach() method along with the JavaScript ternary operator.

<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>
      <div>
        <input type="text" id="searchType">(hit TAB after entering data)
      </div>
      <p id="count"></p>

      <script>
      // Retrieve DOM element references only once:
      let input = document.getElementById("searchType");
      let output = document.getElementById("count");
      
      input.addEventListener("change", count);

      function count(){
        var bloodTypes = ["A+", "O-", "AB+", "O+", "AB+", "AB+", "O-", "AB+", "0+", "AB+"];
        var n = 0;

        bloodTypes.forEach(function(type) {
         // Remember to call .trim on input strings to remove leading and trailing spaces. Utilize the ternary operator in the following manner to streamline the statement:
         // condition ? true value : false value
         n = (type == input.value.trim()) ? n + 1 : n;
        });
        
        output.textContent = n;
      }
      </script>
   </body>
</html>

Answer №3

To ensure that the script runs after the input text box has been filled out, you can add a click handler to a "search" button. Once the button is clicked, the code will execute in response to the 'click' event listener.

If you test the code snippet provided below and input AB+ into the designated box before clicking the search button, the result displayed should be 5, as anticipated:

<div>
  <input type="text" id="searchType">
  <button id="search">Search</button>
</div>
<p id="count"></p>

<script type="text/javascript">

document.getElementById('search').addEventListener('click', () => {
  var bloodTypes = ["A+", "O-", "AB+", "O+", "AB+", "AB+", "O-", "AB+", "0+", "AB+"];
  var n = 0;

  for (var i = 0; i < bloodTypes.length; i++) {
     if (bloodTypes[i] == document.getElementById("searchType").value){
        n++;
     }
  }
  document.getElementById("count").innerHTML = n;
});
</script>

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

Using Angular to pass an index to a pipe function

Currently, I am attempting to incorporate the *ngFor index into my pipe in the following manner: <td *ngFor="let course of courses | matchesTime:time | matchesWeekday:i ; index as i">{{course.courseName}}</td> This is how my pipe is structure ...

Copying a Pinia state Array without referencing it is not possible

My goal is to duplicate an array within a Pinia store so that I can use it to create a reactive object in various components for input modeling. The intention is to only update the original array if the user decides to save any changes made using the copy ...

Is it possible to use Koajs without needing to include the --harmony tag?

Following the merge of iojs into Node, I assumed that I could run koajs without the need for the --harmony tag (as it would have support for generators from es6). Inside my server.js file, I have the following code: var koa = require('koa'); va ...

How can you effectively load shared header and panel HTML onto pages located in separate directories using jQuery Mobile?

I am currently developing a multi-page application utilizing jQuery Mobile and incorporating loadPage() to retrieve various pages. The overall structure is outlined below. landing.html /app-pages/page1.html /app-pages/page2.html /app-pages/page3.html ...

What are the advantages of choosing express.js over Ruby on Sinatra?

Currently brainstorming for a social app and contemplating the switch from my initial option, Sinatra/Ruby to express.js/nodejs. My main focus is on the abundance of open source projects in Ruby that can expedite development. Another major consideration i ...

I am looking for a way to transfer data collected from an input form directly to my email address without the need to open a new window. As of now, I am utilizing angular

Is there a way to send this data to my email address? I need help implementing a method to achieve this. {Name: "John", phoneNumber: "12364597"} Name: "John" phoneNumber: "12364597" __proto__: Object ...

The most efficient method for handling a vast amount of data in NodeJS

My database consists of 4 million numbers and I need to quickly check if a specific number exists in it. Example of the database: [177,219,245,309,348,436,...] I initially tried using a MySQL table for this task, but it took a lengthy 1300ms just to chec ...

Identify dead hyperlinks on a webpage with the help of selenium webdriver while steering clear of links that

I have been trying to identify broken links on a webpage by extracting all anchor tags. However, some of the links are dynamically generated through JavaScript. When I attempt to print out the list of all the links, I encounter a StaleElementReferenceExcep ...

What is the best way to create a test for my Vue component using Jest?

Below is the login form component that needs to be tested for various scenarios: Verify successful login with both username and password filled Check for input error when either username or password is left blank Ensure input error is thrown when only us ...

Leverage videojs-vr within a Vue.js component

I have been experimenting with integrating the videojs-vr package, which I installed through npm, into a Vue.js component. However, I encountered an error: TypeError: videojs is not a function at VueComponent.mounted (VR.vue?d2da:23) at callHook (vue.esm. ...

Removing unexpected keys during validation using Joi

Within my server-side JavaScript code, I am utilizing Joi for validating a JavaScript object. The schema being used is structured as follows: var schema = Joi.object().keys({ displayName: Joi.string().required(), email: Joi.string().email(), e ...

Encountering a mixed content error in Internet Explorer 8 due to the Nivo slider jQuery?

I am encountering an issue with the Nivo jQuery slider on my HTTPS website, as it appears to be generating a mixed content error in Internet Explorer 8. Despite posting on the Dev7 Studios forum and conducting extensive research on the IE 8 mixed content ...

What is the best way to serve individual static files in Express without revealing the entire "/static" directory?

For my new project, I am working on a simple setup that involves using JWT for authorization. The project is being served entirely through express, with no separation between frontend and backend. My goal is to dynamically serve specific HTML files based o ...

Tips for incorporating the "build" directory into the Travis-CI build process and deployment of an npm module

Currently, I am working with a Typescript module that has a directory ./src And I also have travis-ci set up for the project. language: node_js node_js: - 5.1.0 install: - npm install - npm install -g mocha - npm install -g gulp - npm install -g tsd - ...

Sending information to a jQuery UI Dialog

I'm currently working on an ASP.Net MVC website where I display booking information from a database query in a table. Each row includes an ActionLink to cancel the booking based on its unique BookingId. Here's an example of how it looks: My book ...

Retrieving JSON data by key through ajax does not show the expected output

I'm currently working with JSON data in the form of an array, and I'm facing some issues. Here's how the data looks: [ { "id": 1, "name": "Leanne Graham", "username": "Bret", ...

How to achieve the wrapping functionality in ReactJS that is similar to

Is there a ReactJS equivalent to jQuery's wrap method? I want to wrap menuContents with the following element: <ul className="nav nav-pills nav-stacked"></ul> The contents of menuContents are generated like this: let menuContents = thi ...

Datagrid in AngularJS does not update filters upon refresh

Currently, I am attempting to implement name filtering with Angular JS using the following library: https://github.com/angular-data-grid/angular-data-grid.github.io. However, an issue arises when searching as the results do not refresh immediately; only up ...

Issue encountered in loading css and js folders during the build of the Angular2 application due to the files not being found

I have developed an Angular 2 application that utilizes Node.js server APIs. After building the app using nd b, the files were generated in the dist folder. Where should I specify the production URL for the build so that all CSS and JS files load properly? ...

Implementing dynamic props in Vue2 component by passing arbitrary named variables

Having recently delved into Vue, I am facing a challenge that has left me scratching my head after consulting the documentation: I am struggling to pass an arbitrarily named variable as a prop to a component instance. As per my understanding, props serve ...