Problem:
I have an input box with type=”search” and below that a list of options that shows in a dropdown when the input box is clicked. I managed to get this to work.
However the issue I run into now: whenever the ‘X’ in the input box (the search-cancel-button) is clicked the input text in the input box is deleted but the dropdown doesn’t disappear.
How could I fix this?
Below is my code:
.form .formtextbox {
position: relative;
display: inline-block;
width: 100%;
}
.form .formtextbox .options {
display: none;
position: absolute;
background-color: var(--white);
min-width: 100%;
box-shadow: 0px 2px 7px 0px #0000001F;
padding: 12px 16px;
z-index: 1;
}
.form .formtextbox:focus-within .options {
display: block;
}
<form method="get" action="">
<fieldset class="form">
<div class="formtextbox">
<input title="search_form_title" type="search" placeholder="Search" autocomplete="off">
<div class="options">
<ul unselectable="on">
<li>apple</li>
<li>banana</li>
<li>pineapple</li>
<li>strawberry</li>
</ul>
</div>
</div>
<div class="formbutton">
<input type="submit" hidden />
</div>
</fieldset>
</form>
Solution:
One way to do this is to use a little JavaScript. What I have done is added a function which listens for the X
button click event and then hides the dropdown options. The X
button does not dispatch the click event, but rather an input
event. We can listen for the same and hide the dropdown options when it occurs. Additionally, I have added ids
to input and options element to refer them in Javascript. You can use follow other ways well. Something like:
document.getElementById('search-input').addEventListener('input', function() {
var options = document.getElementById('options-container');
if (this.value.length === 0) {
options.style.display = 'none';
} else {
options.style.display = 'block';
}
});
.form .formtextbox {
position: relative;
display: inline-block;
width: 100%;
}
.form .formtextbox .options {
display: none;
position: absolute;
background-color: var(--white);
min-width: 100%;
box-shadow: 0px 2px 7px 0px #0000001F;
padding: 12px 16px;
z-index: 1;
}
.form .formtextbox:focus-within .options {
display: block;
}
<form method="get" action="">
<fieldset class="form">
<div class="formtextbox">
<input id="search-input" title="search_form_title" type="search" placeholder="Search" autocomplete="off">
<div id="options-container" class="options">
<ul unselectable="on">
<li>apple</li>
<li>banana</li>
<li>pineapple</li>
<li>strawberry</li>
</ul>
</div>
</div>
<div class="formbutton">
<input type="submit" hidden />
</div>
</fieldset>
</form>