I am trying to implement a text field with dropdown search. The drop down items are buttons inside a div which has display: none
CSS property. When I click it, The text field should change its content to the content of the button.
The problem is that the dropdown should disappear when the focus is removed from text field. When I click an item of dropdown, the focus is removed, the button disappears and its onclick
doesn't get executed. Is it possible to execute button code which selects name before executing the code which removes this button?
function showNames() {
document.getElementById("dropdown_names").style.display = 'block'
}
function hideNames() {
document.getElementById("dropdown_names").style.display = 'none'
}
function selectName(name) {
document.getElementById("name_inp").value = name
}
#resident_name_inp:focus {
outline: 3px solid #ddd;
}
.dd {
position: relative;
display: inline-block;
}
.dd-content {
display: none;
position: absolute;
background-color: #f6f6f6;
overflow: auto;
width: 100%;
border: 1px solid #ddd;
z-index: 1;
}
.dd-content button {
background-color: #ffffff;
width: 100%;
padding-left: 4px;
border: none;
display: block;
}
.dd-content button:hover {
background-color: #ddd;
}
<div class="dd">
<input
id="name_inp"
type="text"
placeholder="Search Names..."
onfocus="showNames()"
onfocusout="hideNames()">
<div id="dropdown_names" class="dd-content">
<button type="button" onclick="selectName('alex')">alex</button>
<button type="button" onclick="selectName('jake')">jake</button>
<button type="button" onclick="selecttName('evgen')">evgen</button>
</div>
</div>
You can use relatedTarget to check if you clicked on a button element related to the input. Heres what to edit:
function hideNames() {
if(event.relatedTarget != null){
if(event.relatedTarget.tagName == 'BUTTON'){
return
}
}
document.getElementById("dropdown_names").style.display = 'none'
}
function selectName(name) {
document.getElementById("name_inp").value = name
document.getElementById("dropdown_names").style.display = 'none'
}