In my current project, I am utilizing datalist to present a list of choices. The issue I am facing is that both the value and text are being displayed in the dropdown, as expected with datalist. However, I specifically need to hide the value and only show the text.
After extensive research, I came across a solution that involves using data-value
instead of just value
. Despite implementing this change, I have been unsuccessful in getting it to work as intended. The reason I am sticking with datalist is that I require a functional searchable dropdown for my project. Otherwise, I would have abandoned it altogether.
The code snippet I am working with is as follows:
var myinput = document.getElementById('example');
var divs = document.querySelectorAll('.hidden');
myinput.addEventListener('change', function() {
var mydiv = document.getElementById(this.value);
divs.forEach(div => {
div.style.display = div.id === this.value ? 'block' : 'none';
});
});
.hidden {
display: none;
}
<fieldset>
<legend>This is a datalist</legend>
<input type="text" id="example" list="brow" />
<datalist id="brow">
<option value="div1">Choice 1</option>
<option value="div2">Choice 2</option>
</datalist>
</fieldset>
<div class="hidden" id="div1">This is div1</div>
<div class="hidden" id="div2">This is div2</div>