Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript autocomplete without external library

Is there a javascript autocomplete library that does not depend on any other libraries?

I am not using jQuery or the likes as I am making a mobile app that I need to keep extra light.

like image 256
Billy Moon Avatar asked Jul 09 '12 23:07

Billy Moon


People also ask

How would you implement autocomplete suggestions while typing?

Click Search features from the menu on the left and then click the Autocomplete tab. Click on the slider to set Enable autocomplete to On. It can take up to 2-4 days for autocompletions tailored to your search engine to start appearing.

How can create autocomplete search box in jquery?

Syntax: $("TagId"). autocomplete({ source : itemList // List of Words. })


2 Answers

Here is a basic JavaScript example, which could be modified into an autocomplete control:

var people = ['Steven', 'Sean', 'Stefan', 'Sam', 'Nathan'];    function matchPeople(input) {    var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');    return people.filter(function(person) {      if (person.match(reg)) {        return person;      }    });  }    function changeInput(val) {    var autoCompleteResult = matchPeople(val);    document.getElementById("result").innerHTML = autoCompleteResult;  }
<input type="text" onkeyup="changeInput(this.value)">  <div id="result"></div>
like image 163
svnm Avatar answered Sep 18 '22 03:09

svnm


For anyone looking at this in 2017 onwards who needs a simple solution, you can use HTML5's built-in <datalist> tag instead of relying on JavaScript.

Example:

<datalist id="languages">   <option value="HTML">   <option value="CSS">   <option value="JavaScript">   <option value="Java">   <option value="Ruby">   <option value="PHP">   <option value="Go">   <option value="Erlang">   <option value="Python">   <option value="C">   <option value="C#">   <option value="C++"> </datalist>  <input type="text" list="languages"> 

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist

like image 27
Optimae Avatar answered Sep 20 '22 03:09

Optimae