Skip to content Skip to sidebar Skip to footer

Html Datalist: Is There A Way To Autocomplete Based Character Order?

If I enter 'I' in the box, I get India, United States, United Kingdom and Israel. REASON: All have an 'i' in them...somewhere. This seems silly, to me any way. My thinking is it s

Solution 1:

As per my understanding you can't do that with pure HTML. However with the help of JavaScript you can achieve it.

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;
          }
        });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text"list="countries"name="mycountry"id="countryInput" /><datalistid="countries"><optionvalue="India">India</option><optionvalue="United States">United States</option><optionvalue="United Kingdom">United Kingdom</option><optionvalue="Germany">Germany</option><optionvalue="France">France</option><optionvalue="Israel">Israel</option></datalist>

JSFiddle Link

Solution 2:

From what I see, browsers (that support this) do substring matches. In fact, Chrome used to only match at front, but was updated to match in the middle (https://bugs.chromium.org/p/chromium/issues/detail?id=153991). I would say you need to skip datalist and use a custom JS-based approach instead.

Post a Comment for "Html Datalist: Is There A Way To Autocomplete Based Character Order?"