I am using datalist to display a selection of choices. When showing these choices both tha value and text are displaying, like datalist is supposed to work. However, I need to hide the value from the list, onsly showing text.
After a lot of searching I have found out that using data-value is supposed to work, instead of just value. The problem is that I dan't get it to work. The reason I am using datalist is that I need to have it in order to get a functional searchable dropdown. If it wasn't for that I would have dropped it.
My code 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>
It gives priority to your value in dataList, please make sure your option value and option text remain same so that duplication can be avoided
<fieldset>
<legend>This is a datalist</legend>
<input type="text" id="example" list="brow" />
<datalist id="brow">
<option value="Choice 1">Choice 1</option>
<option value="Choice 2">Choice 2</option>
</datalist>