JavaScript Auto Complete for Text Field

Yesterday, I had a project that required me to create an auto complete feature for a text field. I searched for an existing solution online and couldn’t find one that fit my exact needs, so I created my own.  I created this particular solution using both PHP and JavaScript, but it could easily be modified to use only JavaScript if you prefer. However, if you have a long list of words or phrases you need to use for the auto complete feature, then you too may want to use PHP to call them into the JavaScript code as I have done.

A Working Example

Let’s start off by showing you a live working example so you can see what we are creating. Here is the link to the example I made as a proof of concept for the project I was working on:

Type of Auto Complete

This particular type of auto complete feature is used on a regular text input field within a form. This auto complete feature is for when you have a list of words and/or phrases that you want to be made available as input into a text field. It is up to you if you want to allow values outside of that list or not. In my case I do not restrict my text field to values from the list, but I did consider it.

Why I Created a New Auto Complete Feature

I made this solution because I was working on a site for the country of Switzerland and had a need to allow Swiss users to enter a Swiss city into a form. I soon discovered that there are well over two thousand villages, towns and cities throughout Switzerland. I found a list that is supposed to contain all of the municipalities in Switzerland online. I wanted to make a script that would use that list for the auto complete feature for the city text field in that form. My solution allows for larger sized word/phrase lists to be employed with the auto complete feature for any text field you assign.

The Solution

Finally, let’s see some code! The code is mostly JavaScript with a bit of PHP. PHP is optional in this case, so if you desire a pure JavaScript solution, simply exclude the PHP file and hard-code the word/phrase list into the JavaScript code.

The Completed Code

Here is all the code from the cities.php file which is a full working example solution when paired with the towns.txt file which has the list of cities in it. Read the instructions provided near the end of this article to learn how to recreate a working example on your own server.

border: 1px solid #ccc;
cursor: pointer;
//isGood JS function checks if char is a valid letter or not:
function isGood(c) {
return c.toLowerCase() != c.toUpperCase();

var first = ”;//used in suggest function to hold first letter entered into text field
var second = ”;//used in suggest function to hold 2nd letter entered into text field
var third = ”;//3rd letter…
var fourth = ”;//…
function suggest(c){
//build an array of cities:
var cities = [
$file = fopen(“towns.txt”, “r”) or exit(“Unable to open towns.txt file!”);
//Output a line of the file until the end is reached:
while(!feof($file)) {
$line = fgets($file);
$curcity = trim($line);
echo “\”$curcity\”,”;
}//end while reading in lines from keywords.txt file
document.getElementById(‘town’).style.display=”;//shows the suggestions dropdown(town div)
//if only one letter so far:
if(c.length == 1){
//get first letter of c(what was entered into text field) and save it in “first” global variable:
first = c[0].toLowerCase();
if(c.length > 1){
second = c[1].toLowerCase();
second = ”;

if(c.length > 2){
third = c[2].toLowerCase();
third = ”;

if(c.length > 3){
fourth = c[3].toLowerCase();
fourth = ”;

con = ”;//empties contents of suggestions saved previously.
document.getElementById(‘town’).innerHTML = ”;//empties the suggested cities first…
document.getElementById(‘town’).innerHTML = con;//fills the town div with suggested cities
}//end if letter is good
}//end suggest JS function by Ian L. of

var con = ”;//init a variable to hold content of the dropdown of suggested cities
//function ran for ea. city in the cities array:
function foreachfunction(city, index){
//get first letter of city:
var f = city[0].toLowerCase();
//see if first matches 1st letter of city(f):
if(f == first){//adds city to suggestions only if first letter is entered in text input:
//if more than one letter has been entered into text field, get 2nd letter of city too:
if(second != ”){//second is blank if only 1 letter, so if it’s not blank get 2nd letter:
if(city.length > 1)var s = city[1].toLowerCase();
if(city.length > 2)var t = city[2].toLowerCase();
if(city.length > 3)var f = city[3].toLowerCase();
if(fourth != ”){//fourth is blank only if 1,2,3 letters, so if it’s not blank, get 4th letter:
if(f == fourth && t == third && s == second){
con += “<div onclick=’addItem(this.innerHTML)’>”+city+”</div>”;
if(third != ”){//third is blank if only 1 or 2 letters, so if it’s not blank get 3rd letter:

if(t == third && s == second){
con += “<div onclick=’addItem(this.innerHTML)’>”+city+”</div>”;

if(s == second){
con += “<div onclick=’addItem(this.innerHTML)’>”+city+”</div>”;

con += “<div onclick=’addItem(this.innerHTML)’>”+city+”</div>”;
}//end foreachfunction JS function used within above suggest JS function by Ian L.

//function ran when one of the suggested cities is clicked upon:
function addItem(x){
}//end addItem JS function by Ian L. of
Village / Town:<input style=”width:200px” type=”text” id=”city” name=”city” onkeyup=”suggest(this.value)” /><br />
<div style=”display:none;” id=”town” name=”town”>
<input type=”submit” id=”s” name=”s” value=”Suche” />

The Word and/or Phrase List

In this example we have a long list of Swiss cities as our word list. Your word list can be a list of words and/or phrases which you would like to suggest as values to be entered into the text field for which you are applying the auto complete feature to. Each word or phrase can be as long as you like and should be formatted in a plain .txt file with one word and/or phrase per line. Generally you should probably try to keep your phrases short, but there is no actual limit that I am aware of regarding how long they can be. Just remember this is a “text” input not a “textarea” input, so it is meant for short values typically of one to six words approximately. My list is of city names so they are all relatively short and I’ve formatted the .txt file to list one city per line and saved it as “towns.txt” I have uploaded towns.txt to my personal server, so if you would like to copy it to use for testing your own script, you can do so by going to the following url and simply copying and pasting the word list into your own .txt file and naming it “towns.txt”. Here is the link to towns.txt:

Instructions to recreate your own auto complete feature

Follow these simple instructions if you want to create the live example on your own server. Then you may modify the code to fit your individual needs.

  1. First, copy the entire code example above in green text and save it to a .php file. I named my file cities.php, you can name yours whatever you like as long as it ends in “.php”.
  2. follow the above link to the towns.txt file and copy and paste it into a new .txt file and name it “towns.txt”. If you choose to name it something else, be sure to also change the name in the code wherever it is used by doing a search and replace for “towns.txt” and replacing it with your new name if you so choose.
  3. Upload both the PHP file and the TXT file to your server inside of the same directory. Then finally, you can visit the cities.php page in your browser and see it work! That’s all there is to it.

Creating a Pure JavaScript Solution Instead

If you prefer to have a pure JavaScript solution and your word list isn’t too large to handle within the JavaScript, follow these simple instructions:

  1. Follow the above instructions, but while doing step no. 1 above, after copying the green text above to a blank file, find the PHP section of code and simply delete it. Delete everything from “<?php” to after the closing PHP tag that looks like this: “?>”.
  2. Then where the php used to be, add the following code but replace the “one, two, three, four” text with your own personal word and/or phrase list.
    “four” , so your cities variable will look like t his now:
    var cities = [
  3. Then you can save your file as an HTML file now since there is no more PHP code in it, so save it as cities.html and open it in your browser and it should work even from your desktop since HTML doesn’t require a server to function like PHP does.


That’s all there is to it! Feel free to modify this code to fit your needs as you wish. I hope it helps someone else as it did me. I found it very useful myself. I used this on a WordPress site as well, so it is WP friendly FYI.




Leave a Reply

Your email address will not be published. Required fields are marked *