HomeCSSAutocomplete Suggestions On Input Field With Javascript

Autocomplete Suggestions On Input Field With Javascript

Hello and welcome to today’s tutorial. In today’s tutorial, we will learn how to create autocomplete suggestions on an input field. To build this project, we will use HTML, CSS and Javascript.

You can find autocomplete commonly used in forms – either in the search input or text input. The reason why autocomplete is necessary is it saves the users time by suggesting the most relevant inputs.

When the user starts typing in the input field, a list of words that match the user entered text is displayed. The letters in words from the list that match the entered text are emphasized by making them bold. The user can click on any suggested words to use them as the value from the input field.

Video Tutorial:

If you would like to code along with me, you can watch the video version of this tutorial here down below. Also, I post new tutorials on my youtube channel every alternate day. So be sure to subscribe to my channel so you don’t miss any of these tutorials.

 

Project Folder Structure:

Before we start to code, let us first create the project folder structure. We create a project folder called – ‘Autocomplete Input’. Within this folder, we have three files. We name these files index.html, style.css and script.js. These three files are the HTML document, the stylesheet and the script file respectively.

HTML:

We start by creating the basic structure of the project using HTML. First, copy the code below and paste it into your HTML file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Automcomplete Input</title>
    <!-- Google Font -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <form autocomplete="off">
      <div>
        <input type="text" id="input" placeholder="Type a name here..." />
      </div>
      <ul class="list"></ul>
    </form>
    <!--Script-->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Now to make this input field look better, we apply some CSS. Now copy the code provided to you below and paste it into your stylesheet.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  height: 100vh;
  background: linear-gradient(135deg, #8052ec, #d161ff);
}
form {
  width: 75vmin;
  height: 100%;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  padding: 40px 0;
}
input[type="text"] {
  width: 100%;
  padding: 15px 10px;
  border: none;
  border-bottom: 1px solid #645979;
  outline: none;
  border-radius: 5px 5px 0 0;
  background-color: #ffffff;
  font-size: 16px;
}
ul {
  list-style: none;
}
.list {
  width: 100%;
  background-color: #ffffff;
  border-radius: 0 0 5px 5px;
}
.list-items {
  padding: 10px 5px;
}
.list-items:hover {
  background-color: #dddddd;
}

Javascript:

Finally, to add functionality to this project, we use javascript. Now copy the code below and paste it into your script file.

let names = [
  "Ayla",
  "Jake",
  "Sean",
  "Henry",
  "Brad",
  "Stephen",
  "Taylor",
  "Timmy",
  "Cathy",
  "John",
  "Amanda",
  "Amara",
  "Sam",
  "Sandy",
  "Danny",
  "Ellen",
  "Camille",
  "Chloe",
  "Emily",
  "Nadia",
  "Mitchell",
  "Harvey",
  "Lucy",
  "Amy",
  "Glen",
  "Peter",
];
//Sort names in ascending order
let sortedNames = names.sort();

//reference
let input = document.getElementById("input");

//Execute function on keyup
input.addEventListener("keyup", (e) => {
  //loop through above array
  //Initially remove all elements ( so if user erases a letter or adds new letter then clean previous outputs)
  removeElements();
  for (let i of sortedNames) {
    //convert input to lowercase and compare with each string

    if (
      i.toLowerCase().startsWith(input.value.toLowerCase()) &&
      input.value != ""
    ) {
      //create li element
      let listItem = document.createElement("li");
      //One common class name
      listItem.classList.add("list-items");
      listItem.style.cursor = "pointer";
      listItem.setAttribute("onclick", "displayNames('" + i + "')");
      //Display matched part in bold
      let word = "<b>" + i.substr(0, input.value.length) + "</b>";
      word += i.substr(input.value.length);
      //display the value in array
      listItem.innerHTML = word;
      document.querySelector(".list").appendChild(listItem);
    }
  }
});
function displayNames(value) {
  input.value = value;
  removeElements();
}
function removeElements() {
  //clear all the item
  let items = document.querySelectorAll(".list-items");
  items.forEach((item) => {
    item.remove();
  });
}

That’s it for this tutorial. I hope you enjoyed this tutorial. If you are facing any issues while creating this project, you can download the source code. To download the source code, click on the download button below. If you have any doubts, suggestions, or feedback, do leave them in the comments below.
Happy Coding!

RELATED ARTICLES

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

14 − twelve =

Most Popular