Reputation: 6573
I am using HTML5 Datalist for autosuggestion in my project. By default HTML5 follows the keyword contains approach rather then starts with approach. For example, if i have a datalist of one,two,three means if i type 'o' in the search box, it is showing both one and two.but what i am expecting is to show only one in the autosuggestion list.guys pleas help me out how to achieve this.
<input list="sampleList" >
<datalist id="sampleList">
<option value="one">
<option value="two">
<option value="three">
</datalist>
Upvotes: 5
Views: 1720
Reputation: 1751
A possible duplicate to: HTML datalist: Is there a way to autocomplete based character order?.
JSFiddle Link by Buddhi Madarasinghe from the site above.
<input type="text" list="countries" name="mycountry" id="countryInput" />
<datalist id="countries">
<option value="India">India</option>
<option value="United States">United States</option>
<option value="United Kingdom">United Kingdom</option>
<option value="Germany">Germany</option>
<option value="France">France</option>
<option value="Israel">Israel</option>
</datalist>
You can achieve it with the help of JavaScript.
var initialArray = [];
initialArray = $('#countries option');
$("#countryInput").keyup(function() {
var inputVal = $('#countryInput').val();
var first = [];
first = $('#countries option');
if (inputVal != '' && inputVal!= 'undefined') {
var options = '';
for (var i = 0; i < first.length; i++) {
if (first[i].value.toLowerCase().startsWith(inputVal.toLowerCase())) {
options += '<option value="' + first[i].value + '" />';
}
}
document.getElementById('countries').innerHTML = options;
}
else
{
var options = '';
for (var i = 0; i < initialArray.length; i++) {
options += '<option value="' + initialArray[i].value + '" />';
}
document.getElementById('countries').innerHTML = options;
}
});
You can even modify the code for different search queries: JSFiddle Link
Upvotes: 1