Conceal the autofill suggestions when clicking away from the input field

I've created an autofill search feature where the form field populates a dropdown of results from an array as you type into it.

However, I'm facing an issue where the dropdown disappears when clicked outside of it, and then doesn't reappear when typing into the field again. I'm attempting to address this using jQuery:

To display the dropdown under the search field:

const input = document.querySelector('#FAVORITE_LOCATION');
const suggestions = document.querySelector('.suggestions ul');
const country = ['USA', 'Canada'];

function search(str) {
    let results = [];
    const val = str.toLowerCase();

    for (i = 0; i < country.length; i++) {
        if (country[i].toLowerCase().indexOf(val) > -1) {
            results.push(country[i]);
        }
    }

    return results;
}

function searchHandler(e) {
    const inputVal = e.currentTarget.value;
    let results = [];
    if (inputVal.length > 0) {
        results = search(inputVal);
    }
    showSuggestions(results);
}

function showSuggestions(results) {

    suggestions.innerHTML = '';

    if (results.length > 0) {
        for (i = 0; i < results.length; i++) {
            suggestions.innerHTML += `<li>${results[i]}</li>`;
        }
        suggestions.classList.add('has-suggestions');
    } else {
        results = [];
        suggestions.innerHTML = '';
        suggestions.classList.remove('has-suggestions');
    }
}

function useSuggestion(e) {
    input.value = e.target.innerText;
    input.focus();
    suggestions.innerHTML = '';
    suggestions.classList.remove('has-suggestions');
}

input.addEventListener('keyup', searchHandler);
suggestions.addEventListener('click', useSuggestion);

Below is my attempt to hide the populated autofill:

$(document).on('click', function(event){
    var container = $("ul.has-suggestions");
    if (!container.is(event.target) &&            
        container.has(event.target).length === 0) 
    {
       container.hide();
    }else{
        container.show();
    }
});

Lastly, here's the CSS for the dropdown itself

.search-container {
  position: relative;
}

.search-container input,
.search-container .suggestions {
  width: 100%;
}
.search-container input {
  background-color: white;
  height: 60px;
  padding: 0 10px;
}
.search-container .suggestions {
  position: absolute;
  top: 80px;
}

ul {
  display: none;
  list-style-type: none;
  padding: 0;
  margin: 0;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.2);
  max-height: 200px;
  overflow-y: auto;
}
ul.has-suggestions {
  display: block;
}
ul li {
  padding: 10px;
  cursor: pointer;
  background-color: white;
  color: black;
}

ul.has-suggestions is set to display:block when the user starts to type into the form field, which then shows a populated dropdown. I tried to use an if/else statement and using .show(); but it doesn't seem to work.

I would appreciate any assistance or guidance on resolving this issue!

Thank you!

Answer №1

If you're looking to display or hide autocomplete suggestions, you can achieve it with the following script:

input.addEventListener('blur', function() {
  $("ul.has-suggestions").hide();
})

input.addEventListener('focus', function() {
  $("ul.has-suggestions").show();
})

Note that if you want to see a practical example, check out this codepen demonstration.

For an updated version of the code, here is another example on codepen.

In this second codepen version, the form field is filled with the value clicked by the user.

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

Instructions on removing an HTML element from a div that has the attribute contentEditable

Here is an example of HTML code: <div id="editable" contentEditable="true"> <span contentEditable="false">Text to remove</span> </div> I want to be able to delete the entire span element (along with its text) with just one bac ...

Techniques for executing a non-precise keyword search across all columns of a dataframe in R

I recently imported some old files from a dated system without any accompanying documentation. The challenge now lies in sifting through the data within a large dataframe/matrix with over 300 columns. For instance, consider the sample data below: a <- ...

Erase every class within one second using only Pure Javascript

After trying to remove all classes after a second with no success, I attempted the code below: function copyLink() { var text = document.getElementsByClassName("text"), len = text.length; for(i = 0; i < len; i++) { text[i].classList.ad ...

Validating forms in ReactJS

I have developed a basic form validation feature for React. The inspiration for this project came from the following source: When I try to submit the form, input errors arise within the isValid function. I am seeking assistance in resolving this issue. A ...

Troubleshooting: InnerText not being retrieved in Mozilla Firefox

Check out my JavaScript snippet: function chooseRow(objTR) { for (i = 0; i < ddlModalityList.options.length; i++) { if (ddlModalityList.options[i].text == objTR.cells[1].innerText.trim()) break; } ddlModalityList.options[i].selecte ...

Developing components and injecting them dynamically in Angular 2 using Typescript remotely

I am currently exploring the potential of Angular 2 as a foundational technology for a flexible administration dashboard, emphasizing the need for extensibility and customization. I envision an environment where external developers can create their own c ...

change content of attached document when clicked

On all of my pages, I have included my header.php file. However, I am facing an issue with destroying sessions. Even though I have a logout.php page where I attempt to destroy the session, it is not happening as expected. The session remains registered wit ...

Updating the logo image on mobile devices using responsive CSS styling

My goal is to show a different image to users on mobile devices using only CSS, as I am unable to access the HTML code. On mobile, I used display:none for the header-logo-image img { and then added a background-url to the div to successfully display my alt ...

Ways to retrieve a returned value from mongoose

I am attempting to retrieve a value from a mongoose callback function, but I keep encountering an error stating TypeError: #<Object> is not a function. I understand that it may be tricky to achieve this, but the way I am querying the database require ...

Tips on maximizing efficiency in number game coding

Seeking to create a number using a specified set of 6+ inputs. For instance, aiming for the number 280 with inputs [2,4,5,10,30,50,66], the desired output format would be something like this: ((2+5) * 4 * 10). Each input number can only be used once per s ...

Tips for adding content to a textarea after making manual changes to its existing content

One issue I encountered is with capturing the enter key on an input field and appending it to a textarea. While this works initially, any edits made directly on the textarea seem to disrupt the functionality. How can this be resolved? I have tested this i ...

Guide to optimizing the display of a responsive iframe across various devices such as mobile and desktop

I have implemented the following CSS in an iframe to make it responsive. It works well on desktop browsers, but on mobile browsers, the iframe only displays half of the screen. Can you please review the code below and provide guidance on how to fix this is ...

jQuery enables the creation of fresh form fields

Currently, I am working on a form that initially consists of 2 text input fields. The typical use case involves the user entering a number in one field and their name in the other. Following this, the page updates itself without reloading. However, there a ...

Custom validation for Stripe checkout form

Currently, I am working on setting up a customized Stripe checkout where the total amount is dynamic based on the user's selection in the "isStudent" radio button. Additionally, there is a form on the page that needs to be validated before submission, ...

Calculation of image size in JQuery fails to function properly on Chrome and Safari browsers

CONCEPT This page features a combination of visible and hidden div elements, with the hidden ones becoming visible upon clicking a specific span element. One of these hidden elements contains multiple images with overlaid text that are randomly positioned ...

Ways to conceal a parameter in Angularjs while functioning within the ng-bind directive

I am using Angular to create the final URL by inputting offer information. Below is the code snippet: <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> ...

What are some strategies for preventing the $window.alert function from being triggered within an AngularJS controller's scope?

How can I prevent the alert from appearing on my dashboard? Do you have any suggestions? Thank you! I attempted to override the alert empty function in my controller, but I am still encountering the window alert when I navigate to my page. $window.alert ...

The process of fetching an item from an array in MongoDB

After accepting or canceling a friend request, I am unable to pull it from the array. It seems that when I try to do so, nothing happens. The query matches for 1 document but no documents are actually modified. I noticed that removing the requested_at fi ...

Display the preloaded element as the first item using Javascript

Is there a way to prioritize the loaded elements using JavaScript? I have an array of elements that I pass to a function and make an AJAX call. While the data is loading, I display a loader (.gif). I want to ensure that the loaded elements are shown first ...

Including an anchor element with a specified URL, alongside passing the URL as a property

Having trouble passing a URL to href using a property. I'm attempting to pass the {props.github} value to href, but it's not working as expected. I've set up a property object with a field called github like this: export const projectList ...