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

Select the five previous siblings in reverse order using jQuery's slice method

I have a unique approach to displaying a series of divs where only 5 are shown at a time using the slice() method. To navigate through the items, I include an ellipsis (...) link after every 4th item, which allows users to easily move on to the next set of ...

Preventing Click Events from Firing During Drag in JavaScript

I have implemented a code for dragging containers left or right, which is functioning properly. Users can also click on the "thumb". However, I am facing an issue where a click event occurs even after dragging. I want to ensure that only either drag or cli ...

Looking for an uncomplicated SSO system similar to Google Identity Toolkit but with a customizable UI interface?

I'm really impressed with the Google Identity Toolkit, it's so user-friendly and easy to set up! However, I'm having trouble with the fact that it forces me to use its UI. Is there another option available that will allow visitors to simply ...

Having trouble with uploading an image in Laravel using a modal?

For my laravel inventory system, I am facing an issue with uploading images for products. The old code I used for image upload is not working in my current project where I am utilizing a modal and ajax request to save inputs in the database. Can anyone pro ...

Is it possible to prioritize loading JavaScript before images on a webpage?

My goal is to prioritize loading the js first and then the images for a specific reason. I want the blue rollover effect to be applied immediately upon loading. As the number of images on this page will eventually double, this could potentially become a la ...

Encountering a series of frustrating 404 errors when attempting to submit a React form multiple times

I've been working on developing a new forum using Express and React, but I'm facing challenges with saving form data to the database. Currently, my goal is to store topic titles in a MongoDB collection, with plans to expand to include message con ...

Troubleshooting NodeJS CORS issue with heavy requests for file uploads

I'm currently working on a project that involves an Angular front end and a NodeJS API deployed in production using AWS services like S3 and Elastic Beanstalk. When attempting to upload images, I encounter a CORS error if the image is too large or wh ...

Redirecting in Next.js from an API route

I am in the process of developing a backend application that necessitates user authentication. Within this project, I'm utilizing 2 external APIs: API A: responsible for managing user accounts and sessions API B: utilized for executing CRUD operation ...

Encountering the error message "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" while attempting to identify duplicate entries in my database

I am currently working on a backend written in express.js that handles standard CRUD operations. My ORM of choice is sequelize. Here's the code snippet: import { Sequelize} from 'sequelize'; import User from '../Models/User.js'; im ...

Uncover the solution to eliminating webpack warnings associated with incorporating the winston logger by utilizing the ContextReplacementPlugin

When running webpack on a project that includes the winston package, several warnings are generated. This is because webpack automatically includes non-javascript files due to a lazy-loading mechanism in a dependency called logform. The issue arises when ...

Updating the head() properties in Nuxt.js via asyncData() is not possible

After creating a server-side rendered Vue.js blog with Nuxt.js using Typescript and Ghost, I encountered a problem updating html metatags with data from asyncData(). According to the Nuxt.js documentation, asyncData() is triggered before loading page comp ...

Steps to activate the image viewer for each individual looping image:

I'm struggling with my JavaScript code that fetches images and displays them in a modal view when clicked. The issue I'm facing is that the image view only works for the second and other images, but not for the first one. I know there are issues ...

Warning from Cytoscape.js: "The use of `label` for setting the width of a node is no longer supported. Please update your style settings for the node width." This message appears when attempting to create

I'm currently utilizing Cytoscape.js for rendering a dagre layout graph. When it comes to styling the node, I am using the property width: label in the code snippet below: const cy = cytoscape({ container: document.getElementById('cyGraph&apo ...

What could be the reason for the handleOpen and handleClose functions not functioning as expected?

I am facing an issue with my React component, FlightAuto, which contains a dropdown menu. The functionality I'm trying to achieve is for the dropdown menu to open when the user focuses on an input field and close when they click outside the menu. Howe ...

'Error: The type is missing the 'previous' property - Combining TypeScript with ReactJS'

I am quite new to using reactjs and ts. While I understand the error that is occurring, I am unsure of the best solution to fix it. Currently working with reactjs, I have created an: interface interface IPropertyTax { annul: { current: number; p ...

Merging the `on('click')` event with `$(this)`

Hello everyone, this is my first time posting here. I have a question regarding the possibility of achieving a specific functionality. I would like to attach click events to a series of anchor links and then use the $.get() method to reload some icons. T ...

Setting dynamic routes in Next.js when the basePath is not the root can be done by carefully configuring the routing system

After following a tutorial on setting up my Next.js project to be located in a subfolder (/app), everything was running smoothly. However, I encountered issues when trying to use dynamic routes for certain pages. I attempted three different approaches: ...

I am unable to determine if I have already selected a List Item

My goal is to have a functionality where clicking on "Download Drivers" will open the list, and clicking again will close it. This should be achieved with onclick events only, no hover effects. Additionally, I want the list to remain open even if I click o ...

Trying to add a single value to a specific index in a JavaScript array, but it is mistakenly assigning multiple values at once

Currently tackling a matrix algorithm with an early roadblock. The array at hand is: [ [ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ] ] The goal is to convert it into this: [ [ 0, 0, 0 ], [ 0, 9, 0 ], [ 0, 0, 0 ] ] My plan was to alter the middle value like so ...

Manipulate the timing of css animations using javascript

I am currently working with a progress bar that I need to manipulate using JavaScript. The demo of the progress bar has a smooth animation, but when I try to adjust its width using jQuery $($0).css({'width': '80%'}), the animation disap ...