Reputation: 6169
I have a datalist connected to an input
<input list='typesOfFruit' placeholder="Enter a fruit...">
<datalist id='typesOfFruit'>
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</datalist>
As the user is typing Ap...
How can I make it be already selecting the top suggestion "Apple" so if it is correct they can just hit Enter, rather than have to press the down arrow and then enter.
EDIT: Similar question but no one answered correctly: How to auto select the first item in datalist (html 5)?
I need to auto select the top suggestion WHILE typing, not select the first item in the list statically. So if I press B, Banana will be the top suggestion, and I'd like to know if its possible to have it autofocus on it so the user can hit ENTER instead of down arrow enter
Upvotes: 0
Views: 2617
Reputation: 56
$("form").on('keydown', 'input[list]', function(e){
if(e.keyCode == 9 || e.keyCode == 13){
const oInput = this;
const aOptions = $('#' +$(oInput).attr('list')+ ' option').map(function() {return this.text}).toArray();
var aRelOptions = aOptions.filter(function(sOption){
return new RegExp(oInput.value.replace(/\s+/, ".+"), "gi").test(sOption);
});
if(aRelOptions.length > 0){
this.value = aRelOptions.shift();
}
if(e.keyCode == 13) return false;
}
}).on("change", 'input[list]', function() {
$(this).attr("placeholder", this.value);
this.blur();
}).on('focus', 'input[list]', function() {
$(this).attr("placeholder", this.value);
this.value = "";
}).on('blur', 'input[list]', function() {
this.value = $(this).attr("placeholder");
});
Upvotes: 0
Reputation: 10292
You can do this by maintaining a custom query filter for datalist
options.
Try the below code. You can reduce boiler plate if you already know the options
data in place.
Hope this helps!
var input = document.querySelector("input");
var options = Array.from(document.querySelector("datalist").options).map(function(el){
return el.innerHTML;
}); //Optional if you have data
input.addEventListener('keypress', function(e){
if(e.keyCode == 13){
var relevantOptions = options.filter(function(option){
return option.toLowerCase().includes(input.value.toLowerCase());
}); // filtering the data list based on input query
if(relevantOptions.length > 0){
input.value = relevantOptions.shift(); //Taking the first
}
}
});
<input list='typesOfFruit' placeholder="Enter a fruit...">
<datalist id='typesOfFruit'>
<option>Apple</option>
<option>Orange</option>
<option>Banana</option>
</datalist>
Upvotes: 6