├── README.md
├── index.html
├── query.php
└── index.js
/README.md:
--------------------------------------------------------------------------------
1 | # javascript-autocomplete-demo
2 |
3 | Companion repository for [this article](https://dev.to/stephenafamo/how-to-create-an-autocomplete-input-with-plain-javascript)
4 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Demo auto complete
7 |
8 |
9 |
10 | The form
11 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/query.php:
--------------------------------------------------------------------------------
1 | $value) {
23 | if ($query && strpos(strtolower($value), strtolower($query)) === false) {
24 | unset($values[$key]);
25 | }
26 | }
27 |
28 | echo json_encode(array_values($values));
29 | ?>
30 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 |
2 | window.addEventListener("load", function(){
3 | // Add a keyup event listener to our input element
4 | document.getElementById('name_input').addEventListener("keyup", function(event){hinter(event)});
5 | // create one global XHR object
6 | // so we can abort old requests when a new one is make
7 | window.hinterXHR = new XMLHttpRequest();
8 | });
9 |
10 | // Autocomplete for form
11 | function hinter(event) {
12 | var input = event.target;
13 | var huge_list = document.getElementById('huge_list');
14 | // minimum number of characters before we start to generate suggestions
15 | var min_characters = 0;
16 |
17 | if (!isNaN(input.value) || input.value.length < min_characters ) {
18 | return;
19 | } else {
20 | window.hinterXHR.abort();
21 | window.hinterXHR.onreadystatechange = function() {
22 | if (this.readyState == 4 && this.status == 200) {
23 | var response = JSON.parse( this.responseText );
24 | huge_list.innerHTML = "";
25 |
26 | response.forEach(function(item) {
27 | // Create a new