Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active October 20, 2023 05:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save code-boxx/4abffb1b599c7bab9ffa5b94ff1ac0c0 to your computer and use it in GitHub Desktop.
Save code-boxx/4abffb1b599c7bab9ffa5b94ff1ac0c0 to your computer and use it in GitHub Desktop.
Javascript Autocomplete

JAVASCRIPT AUTOCOMPLETE

https://code-boxx.com/simple-autocomplete-html-javascript/

NOTE

The autocomplete is case-insensitive by default. If you want case sensitive searches, edit autocompete.js - function filter() – Remove both toLowerCase().

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<!DOCTYPE html>
<html>
<head>
<title>JS Autocomplete</title>
<meta charset="utf8">
<style>*{font-family:Arial, Helvetica, sans-serif;box-sizing:border-box}input{padding:10px}</style>
<!-- (A) AUTOCOMPLETE JS + CSS -->
<script src="autocomplete.js"></script>
<link rel="stylesheet" href="autocomplete.css">
</head>
<body>
<!-- (B) INPUT FIELD -->
<input type="text" id="demoA">
<!-- (C) ATTACH AUTOCOMPLETE TO INPUT FIELD -->
<script>
ac.attach({
target: document.getElementById("demoA"),
data: ["诸葛猪哥", "Aaronn", "Baattyy", "Chaarles", "Dionn", "Elly"]
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JS Autocomplete</title>
<meta charset="utf8">
<style>*{font-family:Arial, Helvetica, sans-serif;box-sizing:border-box}input{padding:10px}</style>
<!-- AUTOCOMPLETE JS + CSS -->
<script src="autocomplete.js"></script>
<link rel="stylesheet" href="autocomplete.css">
</head>
<body>
<!-- (A) INPUT FIELD -->
<input type="text" id="demoB">
<script>
// (B) ATTACH AUTOCOMPLETE TO INPUT FIELD
ac.attach({
// (B1) REQUIRED - TARGET FIELD + URL
target: document.getElementById("demoB"),
data: "2b-search.php",
// (B2) OPTIONAL - POST DATA
post: { key: "value" }
});
</script>
</body>
</html>
<?php
// DUMMY SEARCH SCRIPT - DO YOUR OWN!
// E.G. SELECT * FROM `TABLE` WHERE `NAME` LIKE "%SEARCH%"
// (A) DUMMY DATA
$data = ["诸葛猪哥", "Aaronn", "Baattyy", "Chaarles", "Dionn", "Elly"];
// (B) SEARCH
$search = strtolower($_POST["search"]);
$results = [];
foreach ($data as $d) {
if (strpos(strtolower($d), strtolower($search)) !== false) { $results[] = $d; }
}
echo count($results)==0 ? "null" : json_encode($results);
<!DOCTYPE html>
<html>
<head>
<title>JS Autocomplete</title>
<meta charset="utf8">
<style>
*{font-family:Arial, Helvetica, sans-serif;box-sizing:border-box}
#myForm{max-width:500px;padding:20px;background:#f2f2f2}
label,input,.acWrap{display:block;width:100%;box-sizing:border-box}
input{padding:10px} label{padding:10px 0}
</style>
<!-- AUTOCOMPLETE JS + CSS -->
<script src="autocomplete.js"></script>
<link rel="stylesheet" href="autocomplete.css">
</head>
<body>
<!-- (A) AUTOCOMPLETE MULTIPLE FIELDS -->
<form id="myForm">
<label for="dName">Name</label>
<input type="text" id="demoC">
<label for="dEmail">Email</label>
<input type="email" id="dEmail">
<label for="dAge">Age</label>
<input type="text" id="dAge">
</form>
<script>
// (B) ATTACH AUTOCOMPLETE
ac.attach({
// (B1) USE AN ARRAY OF OBJECTS AS SUGGESTIONS
target: document.getElementById("demoC"),
data: [
{D: "诸葛猪哥", dEmail: "zhuge@doe.com", dAge: 67 },
{D: "Aaronn", dEmail: "aaronn@doe.com", dAge: 27 },
{D: "Baattyy", dEmail: "baattyy@doe.com", dAge: 37 },
{D: "Chaarles", dEmail: "chaarles@doe.com", dAge: 47 },
{D: "Dionn", dEmail: "dionn@doe.com", dAge: 57 },
{D: "Elly", dEmail: "elly@doe.com", dAge: 18 }
],
// (B2) OPTIONAL, DO THIS ON SELECT
select : (val, multi) => {
console.log(val); // selected value
console.log(multi); // attached multiple values
},
// (B3) OPTIONAL - DELAY + MIN CHARACTERS
delay: 1000,
min: 2
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>JS Autocomplete</title>
<meta charset="utf8">
<style>*{font-family:Arial, Helvetica, sans-serif;box-sizing:border-box}input{padding:10px}</style>
<!-- (A) AUTOCOMPLETE JS + CSS -->
<script src="autocomplete.js"></script>
<link rel="stylesheet" href="autocomplete.css">
</head>
<body>
<!-- (B) INPUT FIELD -->
<input type="text" id="demoD">
<!-- (C) ATTACH AUTOCOMPLETE TO INPUT FIELD -->
<script>
ac.attach({
target: document.getElementById("demoD"),
data: [
{
D : "Joe Doe (joe@doe.com)",
V : "joe@doe.com"
},
{
D : "Joe Doe (joe123@doe.com)",
V : "joe123@doe.com"
}
]
});
</script>
</body>
</html>
/* (A) AUTOCOMPLETE WRAPPER */
.acWrap {
display: inline-block; /* Or block if you like */
position: relative;
}
/* (B) SUGGESTIONS */
.acWrap .acSuggest {
position: absolute;
top: 100%; left: 0;
z-index: 9;
width: 100%;
background: #fff;
border: 1px solid #eee;
display: none;
}
.acWrap .acSuggest {
list-style: none;
padding: 0;
margin: 0;
}
.acWrap .acSuggest li {
padding: 10px;
}
.acWrap .acSuggest li:hover {
background: #d9e7ff;
cursor: pointer;
}
var ac = {
// (A) PROPERTIES
now : null, // current "focused instance"
// (B) ATTACH AUTOCOMPLETE
// target : target field
// data : suggestion data (array), or url (string)
// post : optional, extra data to send to server
// delay : optional, delay before suggestion, default 500ms
// min : optional, minimum characters to fire suggestion, default 2
// select : optional, function to call on selecting an option
attach : inst => {
// (B1) SET DEFAULTS
if (inst.delay == undefined) { inst.delay = 500; }
if (inst.min == undefined) { inst.min = 2; }
inst.timer = null; // autosuggest timer
inst.ajax = null; // ajax fetch abort controller
// (B2) UPDATE HTML
inst.target.setAttribute("autocomplete", "off");
inst.hWrap = document.createElement("div"); // autocomplete wrapper
inst.hList = document.createElement("ul"); // suggestion list
inst.hWrap.className = "acWrap";
inst.hList.className = "acSuggest";
inst.hList.style.display = "none";
inst.target.parentElement.insertBefore(inst.hWrap, inst.target);
inst.hWrap.appendChild(inst.target);
inst.hWrap.appendChild(inst.hList);
// (B3) KEY PRESS LISTENER
inst.target.addEventListener("keyup", evt => {
// (B3-1) CLEAR OLD TIMER & SUGGESTION BOX
ac.now = inst;
if (inst.timer != null) { window.clearTimeout(inst.timer); }
if (inst.ajax != null) { inst.ajax.abort(); }
inst.hList.innerHTML = "";
inst.hList.style.display = "none";
// (B3-2) CREATE NEW TIMER - FETCH DATA FROM SERVER OR ARRAY
if (inst.target.value.length >= inst.min) {
if (typeof inst.data == "string") { inst.timer = setTimeout(() => ac.fetch(), inst.delay); }
else { inst.timer = setTimeout(() => ac.filter(), inst.delay); }
}
});
},
// (C) FILTER ARRAY DATA
filter : () => {
// (C1) SEARCH DATA
let search = ac.now.target.value.toLowerCase(),
complex = typeof ac.now.data[0]=="object",
results = [];
// (C2) FILTER & DRAW APPLICABLE SUGGESTIONS
for (let row of ac.now.data) {
let entry = complex ? row.D : row ;
if (entry.toLowerCase().includes(search)) { results.push(row); }
}
ac.draw(results.length==0 ? null : results);
},
// (D) AJAX FETCH SUGGESTIONS FROM SERVER
fetch : () => {
// (D1) FORM DATA
let data = new FormData();
data.append("search", ac.now.target.value);
if (ac.now.post) {
for (let [k,v] of Object.entries(ac.now.post)) { data.append(k,v); }
}
// (D2) FETCH
ac.now.ajax = new AbortController();
fetch(ac.now.data, { method:"POST", body:data, signal:ac.now.ajax.signal })
.then(res => {
ac.now.ajax = null;
if (res.status != 200) { throw new Error("Bad Server Response"); }
return res.json();
})
.then(res => ac.draw(res))
.catch(err => console.error(err));
},
// (E) DRAW AUTOSUGGEST OPTIONS
draw : results => { if (results == null) { ac.close(); } else {
// (E1) RESET SUGGESTIONS
ac.now.hList.innerHTML = "";
// (E2) DRAW OPTION
let complex = typeof results[0]=="object";
for (let row of results) {
// (E2-1) SET "DISPLAY NAME"
let li = document.createElement("li");
li.innerHTML = complex ? row.D : row;
// (E2-2) SET SUGGESTION DATA
if (complex) {
if (row.V) { li.dataset.val = row.V; }
let entry = {} , multi = false;
for (let [k,v] of Object.entries(row)) {
if (k!="D" && k!="V") { entry[k] = v; multi = true; }
}
if (multi) { li.dataset.multi = JSON.stringify(entry); }
}
// (E2-3) ON SELECTING THIS OPTION
li.onclick = () => ac.select(li);
ac.now.hList.appendChild(li);
}
ac.now.hList.style.display = "block";
}},
// (F) ON SELECTING A SUGGESTION
select : row => {
// (F1) SET VALUES
ac.now.target.value = row.dataset.val ? row.dataset.val : row.innerHTML;
let multi = null;
if (row.dataset.multi !== undefined) {
multi = JSON.parse(row.dataset.multi);
for (let i in multi) { document.getElementById(i).value = multi[i]; }
}
// (F2) CALL ON SELECT IF DEFINED
if (ac.now.select != null) { ac.now.select(row); }
ac.close();
},
// (G) CLOSE AUTOCOMPLETE
close : () => { if (ac.now != null) {
if (ac.now.ajax != null) { ac.now.ajax.abort(); }
if (ac.now.timer != null) { window.clearTimeout(ac.now.timer); }
ac.now.hList.innerHTML = "";
ac.now.hList.style.display = "none";
ac.now = null;
}},
// (H) CLOSE AUTOCOMPLETE IF USER CLICKS ANYWHERE OUTSIDE
checkclose : evt => { if (ac.now!=null && ac.now.hWrap.contains(evt.target)==false) {
ac.close();
}}
};
document.addEventListener("click", ac.checkclose);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment