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!