3

I am using HTML5 Datalist for autosuggestion in my project.by default HTML5 follows the keyword contains approach rather then starts with appoarch.or 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>
yasarui
  • 6,209
  • 8
  • 41
  • 75
  • http://stackoverflow.com/questions/29154877/use-html5-datalist-autocomplete-with-contains-approach-not-just-starts-wit – Vishnu Bhadoriya Feb 08 '17 at 11:33
  • Does this answer your question? [HTML datalist: Is there a way to autocomplete based character order?](https://stackoverflow.com/questions/40456970/html-datalist-is-there-a-way-to-autocomplete-based-character-order) – Heretic Monkey Aug 30 '23 at 15:05

2 Answers2

0

Only by javascript (perhaps jQuery autosuggest) as default suggestions depends on browser's implementation of the datalist tag. And It's very poor. But, As long as I remember, IE compares only first letter

Alex Smith
  • 311
  • 1
  • 3
  • 14
0

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

NcXNaV
  • 1,657
  • 4
  • 14
  • 23