Tips for displaying a div only when the input value is greater than 0, and hiding it when the value is 0

My goal is to display a div whenever the input contains at least 1 character and hide it when the input is empty. Despite my efforts, I can't seem to make it work no matter what I try.

Here is my initial attempt:

var input = document.getElementById('search');
    input.addEventListener('keypress', function(e) {

        var searchHits = document.getElementById('search-hits');

        if (e.keyCode >= 48 && e.keyCode <= 90) {
            searchHits.style.display = 'block';
        }
        else if (e.keyCode === 8 && input.value === '') {
            searchHits.style.display = 'none';    
        }
    });

This approach fails because a backspace key press (keyCode 8) doesn't trigger as an actual keypress since it doesn't add a character to the input value.

Thinking logically, I came up with this solution:

var input = document.getElementById('search');
    input.addEventListener('keypress', function(e) {

        var searchHits = document.getElementById('search-hits');

        if (input.value.length >= 0) {
            searchHits.style.display = 'block';
        }
        else {
            searchHits.style.display = 'none';    
        }
    });

However, I encountered the same issue again where the backspace wasn't being registered as an actual keypress. I'm stuck on how to fix this for proper functionality. Any suggestions?

UPDATE: I even attempted changing the event from 'keypress' to keydown, keyup, input, and change without success.

Answer №1

const searchInput = document.getElementById('search');
    searchInput.addEventListener('keyup', function(e) {

        const searchResults = document.getElementById('search-hits');

        if (searchInput.value.length > 0) {
            searchResults.style.display = 'block';
        }
        if (searchInput.value.length == 0) {
            searchResults.style.display = 'none';    
        }
    });
  <input type="text" id="search">
  
  <div id="search-results" style="display:none;">
    <li>item 1</li>
    <li>item 2</li>
  </div>

Key points to note:

  • The 'keydown' event won't work effectively without a more complex code, as the value length remains at 1 on keydown even when the input is empty. Using keyup works better in this case.
  • For some reason, using two separate if blocks instead of an if/else statement was necessary for proper functionality.

Answer №2

Consider utilizing the change event.

var searchResults = document.getElementById('search-results');
var searchBar = document.getElementById('search-bar');

searchBar.addEventListener('change', function(e) {
    if (searchBar.value.length) {
        searchResults.style.display = 'block';
    } else {
        searchResults.style.display = 'none';    
    }
});

This event is triggered when there is a change in the input value or when focus shifts away from it.

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

Is there a way for me to display a customized error message using antd components?

During the registration process using React and Antd, if the backend returns the error message "user already registered" after clicking on "Sign up", it should be displayed in the form. You can customize the display as shown below: An example of how the u ...

How can a loading indicator be displayed while retrieving data from the database using a prop in a tabulator?

Incorporating a tabulator component into my vue app, I have set up the Tabulator options data and columns to be passed via props like this: // parent component <template> <div> <Tabulator :table-data="materialsData" :ta ...

Customized Box with MaterialUI Styling

Currently, I am utilizing Material UI 5 for my project. To avoid repeatedly defining the same sx prop every time I create a box, I aim to build a custom box component that ensures all boxes have a consistent appearance. Upon going through the documentation ...

Is there a way to turn off step navigation in bootstrap?

Displayed below is a visual representation of the bootstrap step navigation component. Presently, there is an unseen 'next' button located at the bottom of the page. When this 'next' button is pressed, it transitions from 'step-1 ...

Using Three.js to rotate a sphere (globe) to a different location (city) on the sphere's surface

Currently, I am in the process of creating a spherical globe with predefined locations that are geo-mapped and represented as points. My goal is to highlight these locations by smoothly rotating the globe along its y-axis from one point to another. Despite ...

Retrieving an Enum member based on its value in TypeScript

I am working with an enum called ABC: enum ABC { A = 'a', B = 'b', C = 'c', } In addition, I have a method named doSomething: doSomething(enum: ABC) { switch(enum) { case A : console.log(A); break; case ...

Increasing the Efficiency of Styled Components

It appears to me that there is room for improvement when it comes to checking for props in Styled Components. Consider the following code: ${props => props.white && `color: ${colors.white}`} ${props => props.light && `color: ${c ...

The function req.checkBody does not exist

Currently, I am following the guidance of the Mozilla Express tutorial (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/forms). However, as I reached the section involving express-validator, I encountered a persistent error messag ...

Utilizing nested grouping in mongoose schemas

I am facing a challenge while attempting to execute a nested group query in MongoDB. Is there a way to group data by both date and campaign ID, ensuring that each campaign ID contains a nested array of creatives with their respective data (views and clicks ...

Error: The function isInitial of chunk cannot be found

Currently, I am attempting to build my program using the following command: "build": "NODE_ENV='production' webpack -p", However, I encountered an error message: node_modules/extract-text-webpack-plugin/index.js:267 var shouldE ...

Can you explain the concept of the "node module wrapper function" in the context of Node.js?

Can someone explain to me the concept of a "module wrapper function" and how it affects my code? (function (exports, require, module, __filename, __dirname) { }); ...

Issue with Flex property not being supported in Safari browser

.rq-search-container { position: relative; width: 100%; background: white; display: flex; flex-direction: row; align-items: flex-start; border-radius: 2px; z-index: 30; -webkit-flex: 1 0 15em; } While this code functi ...

Transfer sound data blob to server and store it as a file

Currently, I have 3 buttons on my webpage - one to start recording audio, one to stop the recording, and one to play the recorded audio. Using MediaRecorder makes it easy to capture audio as a blob data. However, I am facing issues when trying to upload th ...

Specialized express Validator for 2 particular fields

I currently have 2 custom validators set up for the fields email and phone. check('phone') .not() .isEmpty() .withMessage('Phone should not be empty') .custom(async phone => { const phoneCheck = await ...

developing a dynamic map with javascript

In the image provided, my concept is for it to initially be without a green tint. However, when the user hovers over specific areas, they would turn green and become clickable links. There are multiple areas in the image, with this being just one example. ...

Transform a 2-dimensional array of numbers into an array of objects labeled with a "row" index

Today my brain seems to be in full-on "fart" mode. Struggling to find a clean solution for this task without resorting to an ugly loop or recursion. I have a 2D array of numbers that looks like this: const layoutMatrix = [ 1, [1], [0.5, 0.5], [0.2 ...

The request for data:image/png;base64,{{image}} could not be processed due to an invalid URL

I am facing an issue with converting image data that I receive from the server using Angular.js for use in ionic-framework. Here is the code snippet I have been working with: $http.post(link, { token: token, reservationCode: reservatio ...

The functionality of Angular animate becomes compromised when there is a conflict between predefined CSS states and transition states

Explore this example CSS code: /* animations at the start */ .error-animation.ng-enter { -webkit-transition: 0.5s linear all; transition: 0.5s linear all; opacity: 0; } ...

The effectiveness of a promise chain is consistent, even when the return statement is subject to conditions

After reorganizing this sequence, I am perplexed at how it continues to function regardless of a conditional return statement in one of the .then sections: function addList(name) { let listObj = {}; listObj.name = name; return nameExists(name) //returns a ...

Reconfigure a portion of a string using Vue's dynamic replacement feature

Currently tackling a problem. In my possession is a string that essentially consists of HTML code: let htmlTitle = "<a href="/news/sky-sport-hd-in-italia-dal-18-novembr">Sky Sport HD in italia dal 18 novembre</a> | <a href="/news/ecco-il-g ...