Auto Completing Field in a Web Page

Introduction

 
In many websites, you can see the autocompletion of some names and places while you are typing. This is a concept of reducing the work for the users using it. It is more effective compared to the dropdown box since in the dropdown box, you need to search the name or place by scrolling down. But here, if you just type the first few letters of the field it will auto-fill it by giving you some suggestions. In this article, we can discuss the creation of a webpage with an auto-fill option for a country name with some autosuggestions.
 

Creating an Autocomplete Field

 
To create an autocomplete field, I am using four programming languages:
  • HTML - For creating basic templates and functions.
  • CSS - Attaching styles to the HTML template.
  • JavaScript - For validation and triggering functions.
  • PHP - For assigning button controls.
HTML and CSS are the two basic languages for creating this webpage. You can use some other languages instead of using PHP and JavaScript.
 

Steps

 
To create an autocomplete field, you can open a new HTML code editing page in your IDE. Here, I am using the Visual Studio Code for this purpose. You can install the Visual Studio Code by clicking here. Here I embedded the codes in the single file, but you can link the different files for style sheet, Javascript, and PHP work.
 
Auto Completing Field In A Web Page
 
You can use the source code given below for creating a page:
  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0">    
  5. <style>    
  6. * {    
  7.   box-sizing: border-box;    
  8. }    
  9.     
  10. body {    
  11.   font: 14px times_new_roman;      
  12. }    
  13.     
  14. /*the container must be positioned relative:*/    
  15. .autocomplete {    
  16.   position: relative;    
  17.   display: inline-block;    
  18. }    
  19.     
  20. input {    
  21.   border: 1px solid transparent;    
  22.   background-color: #f1f1f1;    
  23.   padding: 10px;    
  24.   font-size: 16px;    
  25. }    
  26.     
  27. input[type=text] {    
  28.   background-color: #f1f1f1;    
  29.   width: 100%;    
  30. }    
  31.     
  32. input[type=submit] {    
  33.   background-color: rgb(78, 139, 200);    
  34.   color: #fff;    
  35.   cursor: pointer;    
  36. }    
  37.     
  38. .autocomplete-items {    
  39.   position: absolute;    
  40.   border: 1px solid #d4d4d4;    
  41.   border-bottom: none;    
  42.   border-top: none;    
  43.   z-index: 99;    
  44.   /*position the autocomplete items to be the same width as the container:*/    
  45.   top: 100%;    
  46.   left: 0;    
  47.   right: 0;    
  48. }    
  49.     
  50. .autocomplete-items div {    
  51.   padding: 10px;    
  52.   cursor: pointer;    
  53.   background-color: #fff;     
  54.   border-bottom: 1px solid #d4d4d4;     
  55. }    
  56.     
  57. /*when hovering an item:*/    
  58. .autocomplete-items div:hover {    
  59.   background-color: #e9e9e9;     
  60. }    
  61.     
  62. /*when navigating through the items using the arrow keys:*/    
  63. .autocomplete-active {    
  64.   background-color: DodgerBlue !important;     
  65.   color: #ffffff;     
  66. }    
  67. </style>    
  68. </head>         
  69. <body>    
  70.     
  71. <h1>Autocomplete Of Country name </h1>    
  72.     
  73. <p>Start typing your country name:</p>    
  74.   <div class="autocomplete" style="width:300px;">    
  75.     <input id="myInput" type="text" name="myCountry" placeholder="Country">    
  76.   </div>    
  77.   <input type="submit">    
  78. </form>    
  79.     
  80. <script>    
  81. function autocomplete(inp, arr) {    
  82.   /*the autocomplete function takes two arguments,   
  83.   the text field element and an array of possible autocompleted values:*/    
  84.   var currentFocus;    
  85.   /*execute a function when someone writes in the text field:*/    
  86.   inp.addEventListener("input"function(e) {    
  87.       var a, b, i, val = this.value;    
  88.       /*close any already open lists of autocompleted values*/    
  89.       closeAllLists();    
  90.       if (!val) { return false;}    
  91.       currentFocus = -1;    
  92.       /*create a DIV element that will contain the items (values):*/    
  93.       a = document.createElement("DIV");    
  94.       a.setAttribute("id"this.id + "autocomplete-list");    
  95.       a.setAttribute("class""autocomplete-items");    
  96.       /*append the DIV element as a child of the autocomplete container:*/    
  97.       this.parentNode.appendChild(a);    
  98.       /*for each item in the array...*/    
  99.       for (i = 0; i < arr.length; i++) {    
  100.         /*check if the item starts with the same letters as the text field value:*/    
  101.         if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {    
  102.           /*create a DIV element for each matching element:*/    
  103.           b = document.createElement("DIV");    
  104.           /*make the matching letters bold:*/    
  105.           b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";    
  106.           b.innerHTML += arr[i].substr(val.length);    
  107.           /*insert a input field that will hold the current array item's value:*/    
  108.           b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";    
  109.           /*execute a function when someone clicks on the item value (DIV element):*/    
  110.           b.addEventListener("click"function(e) {    
  111.               /*insert the value for the autocomplete text field:*/    
  112.               inp.value = this.getElementsByTagName("input")[0].value;    
  113.               /*close the list of autocompleted values,   
  114.               (or any other open lists of autocompleted values:*/    
  115.               closeAllLists();    
  116.           });    
  117.           a.appendChild(b);    
  118.         }    
  119.       }    
  120.   });    
  121.   /*execute a function presses a key on the keyboard:*/    
  122.   inp.addEventListener("keydown"function(e) {    
  123.       var x = document.getElementById(this.id + "autocomplete-list");    
  124.       if (x) xx = x.getElementsByTagName("div");    
  125.       if (e.keyCode == 40) {    
  126.         /*If the arrow DOWN key is pressed,   
  127.         increase the currentFocus variable:*/    
  128.         currentFocus++;    
  129.         /*and and make the current item more visible:*/    
  130.         addActive(x);    
  131.       } else if (e.keyCode == 38) { //up    
  132.         /*If the arrow UP key is pressed,   
  133.         decrease the currentFocus variable:*/    
  134.         currentFocus--;    
  135.         /*and and make the current item more visible:*/    
  136.         addActive(x);    
  137.       } else if (e.keyCode == 13) {    
  138.         /*If the ENTER key is pressed, prevent the form from being submitted,*/    
  139.         e.preventDefault();    
  140.         if (currentFocus > -1) {    
  141.           /*and simulate a click on the "active" item:*/    
  142.           if (x) x[currentFocus].click();    
  143.         }    
  144.       }    
  145.   });    
  146.   function addActive(x) {    
  147.     /*a function to classify an item as "active":*/    
  148.     if (!x) return false;    
  149.     /*start by removing the "active" class on all items:*/    
  150.     removeActive(x);    
  151.     if (currentFocus >= x.length) currentFocus = 0;    
  152.     if (currentFocus < 0) currentFocus = (x.length - 1);    
  153.     /*add class "autocomplete-active":*/    
  154.     x[currentFocus].classList.add("autocomplete-active");    
  155.   }    
  156.   function removeActive(x) {    
  157.     /*a function to remove the "active" class from all autocomplete items:*/    
  158.     for (var i = 0; i < x.length; i++) {    
  159.       x[i].classList.remove("autocomplete-active");    
  160.     }    
  161.   }    
  162.   function closeAllLists(elmnt) {    
  163.     /*close all autocomplete lists in the document,   
  164.     except the one passed as an argument:*/    
  165.     var x = document.getElementsByClassName("autocomplete-items");    
  166.     for (var i = 0; i < x.length; i++) {    
  167.       if (elmnt != x[i] && elmnt != inp) {    
  168.         x[i].parentNode.removeChild(x[i]);    
  169.       }    
  170.     }    
  171.   }    
  172.   /*execute a function when someone clicks in the document:*/    
  173.   document.addEventListener("click"function (e) {    
  174.       closeAllLists(e.target);    
  175.   });    
  176. }    
  177.     
  178. /*An array containing all the country names in the world:*/    
  179. var countries = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central Arfrican Republic","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cuba","Curacao","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kiribati","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Myanmar","Namibia","Nauro","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","North Korea","Norway","Oman","Pakistan","Palau","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre & Miquelon","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Korea","South Sudan","Spain","Sri Lanka","St Kitts & Nevis","St Lucia","St Vincent","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad & Tobago","Tunisia","Turkey","Turkmenistan","Turks & Caicos","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States of America","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"];    
  180.     
  181. /*initiate the autocomplete function on the "myInput" element, and pass along the countries array as possible autocomplete values:*/    
  182. autocomplete(document.getElementById("myInput"), countries);    
  183. </script>    
  184.     
  185. </body>    
  186. </html>    

Output Verification

 
After coding, you must save the code with .html. You can find an HTML page in the place where you saved the file.
 
Auto Completing Field In A Web Page
 
Open that file in a browser. There you are able to see a field called country.
 
Auto Completing Field In A Web Page
 
Start typing your country name there, it will automatically suggest the country name for you.
 
Auto Completing Field In A Web Page
 
After choosing that, you can submit.
 
Auto Completing Field In A Web Page
 

Conclusion

 
This is an option to help the users of the website. You can use this code while you are developing a website. You can load it into the server and then use it.