What could be the reason for the absence of search results in my searchbox?

Can anyone assist me in identifying the issue with my search box? I have created a JavaScript search box that validates input against a predefined keyword list. If a word matches, the "HARMI-SOIL 8.0/15 Result Box" should be displayed, otherwise it should remain hidden (display:none).

The problem I am facing is that after entering a matching word and pressing enter, the Result Box does not appear. Javascript indicates that the words do not match, even though they should. However, when I click on the cross (x) and delete the input, the Result Box shows up and Javascript confirms that the words match. Any tips or hints would be greatly appreciated. Thank you!

var wordsHarmi = [
    "Bodenhilfsstoff",
    "Dünger","Duenger",
    "Harmi",
    "Soil",
    "Harmi-Soil",
    "Boden",
    "Mineralien",
    "Wurzelwachstum",
    "Nährstoffe", "Naehrstoffe",
]

let harmiSuche = document.getElementById('harmi-suche')
const inputSearch = document.getElementById('input-suche');

inputSearch.addEventListener('search', (event) => {
    const searchString = event.target.value.toLowerCase();
    console.log(event);

    
    // Iterate over words array to find the input value
    for (let index = 0; index < wordsHarmi.length; index++) {

        console.log("works");
        
        const wordFound =     wordsHarmi[index].toLowerCase() ==searchString;

        if(wordFound){
            console.log("Word found");
            harmiSuche.style.display = 'flex';
        }
        
        else {
        harmiSuche.style.display = 'none';
        console.log("Word not found");
        }
    }
})
 #harmi-suche{
        display: none;
    }
    .col-1 {width: 100%;}
    .
    <!-- CSS styling continues here -->
<div id="sucheingabe" class=" suchergebnis col-1">
    <!-- HTML content continuation -->

Answer №1

Your code has been successfully updated!

I made some necessary changes to improve the functionality of your code. Check it out.

  1. To enhance performance, I converted all elements in your original array to lowercase, similar to what you did with the inputSearch variable.
  2. The for loop in your code was unnecessary and memory-intensive. Instead, I suggest using Javascript's include function for better efficiency.
  3. A missing input field in the HTML file was causing errors, so I added it in the correct position.
<!-- The search input box should be placed as follows in the index.html file -->
    <input id="input-suche" type="search"/>
    <div id="suchfilter" class="column">
        <div id="harmi-suche" class="item kachel3 device-margin-right device-margin-left">
  1. I also rewrote your JavaScript file. Here is the updated version of the code which has been tested and verified.
//I have changed your variable declaration to 'const' instead of 'var', but you can still use var if you prefer.
const wordsHarmi = [
    "Bodenhilfsstoff",
    "Dünger", "Duenger",
    "Harmi",
    "Soil",
    "Harmi-Soil",
    "Boden",
    "Mineralien",
    "Wurzelwachstum",
    "Nährstoffe", 
    "Naehrstoffe",
];

const harmiSuche = document.getElementById('harmi-suche')
const inputSearch = document.getElementById('input-suche');

// Transform all array elements to lowercase before running the main code
let wordsHarmi_lower = wordsHarmi.map(function(v){
    return v.toLowerCase();
})

inputSearch.addEventListener('search', (event) => {
    const searchString = event.target.value.toLowerCase();

    // Utilize Javascript's includes function for efficient searching in the array
    const found = wordsHarmi_lower.includes(searchString);

    if(found === true){
        harmiSuche.innerHTML = "Congratulations, user found"; 

    } else {
        harmiSuche.innerHTML = "User not found, try again";
    }
})

Answer №2

When a match is identified, it is important to halt the loop (otherwise, it will only apply to the final item in the list :) )

       if(wordFound){
            console.log("Word found");
            harmiSuche.style.display = 'flex';
            break; // <--- this line is crucial!
        } else {
         ......
       }
}

Answer №3

To solve the issue, you must adjust the condition

if(wordFound == true){
        console.log("Word found");
        harmiSuche.style.display = 'flex';
    }

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

Multiple selection menus within a single module

I am working on a component with multiple dropdown menus. <div v-for="(item, index) in items" :key="index"> <div class="dropdown"> <button @click="showInfo(index)"></button> <div ...

The Ultimate Guide to HTML Scrolling Default Pages

I found a JSFiddle link to help me create a sliding page content: http://jsfiddle.net/sg3s/rs2QK/ Although I'm quite pleased with it, I am trying to make the first target show up by default. I attempted to replace the panel class of the first target ...

Update the package.json file by adding a new command to an existing script

Is it possible to automatically run npm install before starting the application with npm start? Here is what my package.json file currently looks like: . . "scripts": { "test": "echo \"Error: no test specified\ ...

Material-UI: The call stack has exceeded the maximum range, causing an Uncaught RangeError

I am currently utilizing the Dialog and Select components offered by Material-UI in conjunction with React. Here is a quick example: import React from 'react'; import { Dialog, MenuItem, Select } from '@material-ui/core'; class Examp ...

Displaying text alongside variables within a foreach loop

I've created a custom script to manage a webpage that includes three checkboxes. Here is the HTML for the checkboxes: <input type="checkbox" value="Ex1" name="Check[]" />Ex1 <input type="checkbox" value="Ex2" name="Check[]" />Ex2 <inp ...

CSS Media Query Assistance - optimizing text display for mobile responsiveness

I am currently facing an issue with my CSS code where the content is displaying as one long sentence on mobile devices, requiring users to scroll to read it. I am trying to modify it so that it displays as two lines on mobile. <!-- promo banner --> ...

The callback function for the `input` component in React Native must be a function and should not be undefined. Always remember to start component names with the proper syntax

There was a gap in my project as I have an application currently under development for testing purposes. Error: The view config getter callback for the component input must be a function (received undefined). Make sure to capitalize component names. I am ...

React - manipulating data with state, yay or nay?

My form has two columns - the left column displays a proposed value for the right column. Currently, I retrieve both values from separate API calls and everything is functioning as expected. This is how my code looks at the moment: const dbContact = useD ...

Node.js allows you to seamlessly upload multiple images from various form fields or input types simultaneously

<form action="/upload-images" method="post" enctype="multipart/form-data"> <input type="file" name="image1" /> <input type="file" name="image2" /> <input type= ...

Attempting to generate two columns out of a list of divs, with additional white space in the left column

I am attempting to render a series of divs into two columns. However, when viewing the example in this [JSFiddle](http://jsfiddle.net/nb32P/2/) link, I noticed there is extra spacing above Group Heading 4 in the left column that I cannot seem to remove. ...

Struggling to configure Velocity Js?

After attempting to use Velocity Js for the first time, I encountered some issues while trying to create a navigation menu. Despite having functioning code and animations, the menu failed to open. I followed the instructions on the Velocity JS site by incl ...

Is it possible to utilize a keyboard listener to activate a tooltip upon being invoked?

I've created a basic pie chart that shows a tooltip when you click on a pie wedge. Now, I want to achieve the SAME functionality, but for div elements located OUTSIDE of the pie chart. Situation: A user focusing on the 'Cat 1' div and ...

Change the display of the lightbox when clicked. Utilize Angular and JQuery for this functionality

Here is the code for a lightbox: <div id="light-box"> <div id="first"> ..... </div> //initially visible <div id="second"> ..... </div> //hidden - but displayed when button is clicked. </div> I want to add two button ...

What is the best way to incorporate 2D collision detection for the lower portion of the obstacles in my game design?

When the square ball bounces off the top of the obstacles but goes straight through if coming from the bottom, what adjustments can I make to the collision detection code to check for collisions from the bottom as well? Any help is greatly appreciated. Her ...

Utilizing getServerSideProps and getInitialProps in Next.js to optimize page loading times

My page is not loading when I use getServerSideProps or getInitialProps. It keeps on loading without displaying the content, but everything works fine when I remove them. What could be wrong with my code here? HELP. ... interface Props { data: any; } co ...

Using ng-class in AngularJS, you can pass a class name to apply to an

I currently have the following code: <tr ng-class="{{line.color}}" ng-repeat="line in gameRank | orderBy: sortType: sortReverse"> <td>{{$index + 1}}</td> <td>{{line.username}}</td> <td>{{line.games}}</td& ...

Struggling with the Nivo slider not loading properly?

Check out my personal website. I'm having an issue with my Nivo slider not displaying properly - it just keeps loading. Any ideas on why this is happening and how I can fix it? Below is the CSS I am using: #slider { position:relative; width: ...

You must include an argument for 'model' in the Angular service

My service requires an id parameter for a route, but when I tried to access the route with the id, I encountered the error mentioned above. Any suggestions on how to resolve this issue? https://i.sstatic.net/FEcqo.png #request const apiBaseUrl = `${envir ...

Implementing jQuery form validator post anti-SPAM verification?

I am facing what seems like a straightforward JavaScript issue, but my knowledge in this area is still limited. Following a successful implementation of basic anti-SPAM feature that asks the user to solve a simple math problem, how can I integrate jQuery& ...

Is it possible to create a jQuery-powered color picker that changes colors in real-time

I am currently working on a form that needs to send data to the database. The form includes fields for the product name and specifications details such as spec name and color selection. While I was able to generate the spec input without any issues, I enco ...