Using a unique solution from @Olli here at Limit total entries displayed by datalist I'm able to limit the number of suggestions offered by a datalist
.
The problem: that solution only allows for searching the option innerHTML
. It doesn't allow for simultaneously searching the datalist option value=
even though datalist
is capable of doing that by default.
For example (see example below), if I type input California
, datalist
doesn't return the California
result, but if I input CA
or CA-US
then datalist
returns the intended California
result.
What changes do I need to make to the Javscript code in order to include the option innerHTML
functionality?
var search = document.querySelector('#search');
var results = document.querySelector('#searchresults');
var templateContent = document.querySelector('#resultstemplate').content;
search.addEventListener('keyup', function handler(event) {
while (results.children.length) results.removeChild(results.firstChild);
var inputVal = new RegExp(search.value.trim(), 'i');
var clonedOptions = templateContent.cloneNode(true);
var set = Array.prototype.reduce.call(clonedOptions.children, function searchFilter(frag, el) {
if (inputVal.test(el.textContent) && frag.children.length < 5) frag.appendChild(el);
return frag;
}, document.createDocumentFragment());
results.appendChild(set);
});
var n = document.getElementById("search");
n.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
<template id="resultstemplate">
<option value="Alabama">AL-US</option>
<option value="California">CA-US</option>
<option value="Michigan">MI-US</option>
<option value="Texas">TX-US</option>
<option value="Wisconsin">WI-US</option>
</template>
<input type="text" name="search" id="search" placeholder="type state name or code" list="searchresults" autocomplete="off" />
<datalist id="searchresults"></datalist>
<button id="myButton" type="button"
onclick="loadDoc('state_data.xml', myFunction)">Submit
</button>