My own autocomplete
by joquery
HTML
<p>Starts autocompleting when 3 characters have been typed</p>
<input type="search" name="searchAirport" id="searchAirport" />
<ul id="autocompleteList"></ul>
CSS
#autocompleteList {
display: block;
background: #bada55;
margin:0;
padding:10px;
list-style-type: none;
}
#autocompleteList li{
color: #fff;
font-family: sans-serif;
border: 1px solid #cacaca;
margin: 2px 0;
background: violet;
padding: 2px 5px;
cursor: pointer;
}
#autocompleteList li:hover{
background: cyan;
}
}
JavaScript
var foundAirports = [];
var searchBox = document.getElementById("searchAirport");
var list = document.getElementById("autocompleteList");
searchBox.oninput = function () {
/* if (searchBox.value === "") {
list.innerHTML = "";
return;
}
*/
var searchText = searchBox.value.toLowerCase();
searchText = searchText.trim();
if (searchText.length < 3) {
list.innerHTML = "";
return;
}
list.style.display = "block";
if (foundAirports.length > 0) {
foundAirports = null;
foundAirports = [];
}
var i = 0;
var arrLen = airports.length;
for (i; i < arrLen; i++) {
var curAirport = airports[i];
var curAirportText = curAirport.name.toLowerCase();
var curAirportIata = curAirport.iataCode.toLowerCase();
if (curAirportText.lastIndexOf(searchText, 0) === 0 || curAirportIata.lastIndexOf(searchText, 0) === 0) {
foundAirports.push(curAirport);
}
}
i = 0;
arrLen = (foundAirports.length > 105) ? 105 : foundAirports.length;
var html = "";
for (i; i < arrLen; i++) {
html += '<li data-value="' + foundAirports[i].iataCode + '">' + foundAirports[i].name + '</li>';
}
list.innerHTML = html;
};
list.addEventListener("click", function(e) {
var el = e.target;
while (el && el.tagName !== "LI") {
el = el.parentNode;
}
searchBox.value = el.innerText;
searchBox.dataset["value"] = el.dataset["value"];
list.style.display = "none";
}, false);
var airports = [
{"name": "28 De Noviembre Airport", "iataCode": "RYO"},
{"name": "A Coruña Airport", "iataCode": "LCG"},
{"name": "A P Hill Aaf (Fort A P Hill) Airport", "iataCode": "APH"},
{"name": "A-306 Airport", "iataCode": "QUN"},
{"name": "Aachen-Merzbrück Airport", "iataCode": "AAH"},
{"name": "Aalborg Airport", "iataCode": "AAL"},
{"name": "Aappilattoq (Kujalleq) Heliport", "iataCode":...