I have an input type="text" linked to a datalist and a button next to it.
I'm trying to open the datalist when the button is clicked (as if the input box was clicked).
how can I acheive that? it seems like there's no simple solution for this, should I use something other than datalist to make it easier and more supported by browsers?
input::-webkit-calendar-picker-indicator {
display: none;
}
<input type="text" list="lst" name="input1" />
<button>open list</button><br>
<input type="text" list="lst" name="input2" />
<button>open list</button>
<datalist id="lst">
<option value="a"></option>
<option value="b"></option>
<option value="c"></option>
</datalist>
let BTN = document.querySelector('button'),
List = document.querySelector('datalist'),
selectBox = document.querySelector('select'),
input = document.querySelector('input'),
options = selectBox.options;
BTN.onclick = ()=>{
if (List.style.display === '') {
List.style.display = 'block';
BTN.textContent = "close list";
let val = input.value;
for (let i = 0; i < options.length; i++) {
if (options[i].text === val) {
selectBox.selectedIndex = i;
break;
}
}
} else HideSelectBox();
}
selectBox.addEventListener('change', ()=>{
input.value = options[selectBox.selectedIndex].value;
HideSelectBox();
});
input.addEventListener('focus', HideSelectBox);
function HideSelectBox () {
List.style.display = '';
BTN.textContent = "open list";
}
select {
width: 185px;
}
datalist {
display: none;}
option {
padding: 3px;
}
option:hover {
background-color: #cccc;
}
input::-webkit-calendar-picker-indicator {
display: none;
}
<label>
<input list='lst'>
</label>
<button>open list</button>
<datalist id="lst">
<label>
<select multiple size=3>
<option value="a">a
<option value="b">b
<option value="c">c
</select>
</label>
</datalist>