Autocomplete on Input Field JavaScript

Autocomplete on Input Field using HTML, CSS & JavaScript

Autocomplete on Input Field using HTML, CSS & JavaScript

Hello everyone. Welcome to today’s tutorial on Codewithrandom. We’ll learn how to make Autocomplete on Input Field which will fill the words as soon as the user will enter the words in the search box. In Today’s session, We will use HTML, CSS, and JavaScript to complete this Autocomplete on Input Field Project.

Project Description

Step 1
The HTML (Hypertext Markup Language) will help us to create the structure for the list with some necessary attributes and elements to makeAutocomplete on Input Field Project.

Step 2
Then we will use CSS (Cascading Stylesheet) which will help us to style or design the project with suitable padding and alignment in the Autocomplete on Input Field Project.

Step 3
At last we will use JS (JavaScript) which will add a logic to make the autocomplete on Input Field Project responsive from the user end.

I hope you have got an idea about the project.

HTML Code for Autocomplete on Input Field

First we’ll start with creating the structure of the Predictive Text On Input Fields project for that as you can see the above code we have used all the necessary elements & attributes to setup the structure. Let us know code the CSS part to add styling and aligned the tags.

<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Predictive Text</title>
    <!-- Google Font -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="input-container">
      <input
        type="text"
        id="input"
        placeholder="Type something here.."
        autocomplete="off"
      />
      <span id="suggestion"></span>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

50+ HTML, CSS & JavaScript Projects With Source Code

CSS Code for Autocomplete on Input Field

Second comes the CSS code in which we have styled for the structure we have padded as well as aligned the Predictive Text On Input Fields project so that it is properly situated and doesn’t get messy with suitable CSS elements. Now lets code the JavaScript part to make responsive.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #2c8df6;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
.input-container {
  position: relative;
  background-color: #ffffff;
  width: 25em;
  height: 4.4em;
  border-radius: 5px;
}
input {
  outline: none;
  border: none;
  background-color: transparent;
  position: absolute;
  width: inherit;
  height: inherit;
  color: #000000;
  font-size: 25px;
  padding: 0 18px;
  z-index: 3;
}
#suggestion {
  width: inherit;
  height: inherit;
  position: absolute;
  z-index: 2;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  padding: 0 18px;
  font-size: 25px;
  color: #868686;
}
@media screen and (max-width: 600px) {
  .input-container {
    width: 80vw;
  }
}

JavaScript Code for Autocomplete on Input Field

Last stage of the project the JavaScript in which we have added the logical and coded as per the requirement with some conditions. Let us see the Final Output of the project Predictive Text On Input Fields using HTML, CSS & JavaScript (Source Code).

let words = [
  "Apple",
  "Pencil",
  "Pen",
  "Chair",
  "Helmet",
  "Grapes",
  "Tub",
  "Trophy",
  "Cookie",
  "Donut",
  "Shirt",
  "Bat",
  "Ash",
  "Bell",
  "Chat",
  "Ball",
  "Eye",
  "Fish",
  "Zip",
  "Game",
  "Juice",
  "Orange",
  "Fan",
  "Ice",
];
words.sort();
let input = document.getElementById("input");
let suggestion = document.getElementById("suggestion");
//Enter key code
const enterKey = 13;

window.onload = () => {
  input.value = "";
  clearSuggestion();
};

const clearSuggestion = () => {
  suggestion.innerHTML = "";
};

const caseCheck = (word) => {
  //Array of characters
  word = word.split("");
  let inp = input.value;
  //loop through every character in ino
  for (let i in inp) {
    //if input character matches with character in word no need to change
    if (inp[i] == word[i]) {
      continue;
    } else if (inp[i].toUpperCase() == word[i]) {
      //if inp[i] when converted to uppercase matches word[i] it means word[i] needs to be lowercase
      word.splice(i, 1, word[i].toLowerCase());
    } else {
      //word[i] needs to be uppercase
      word.splice(i, 1, word[i].toUpperCase());
    }
  }
  //array to string
  return word.join("");
};

//Execute function on input
input.addEventListener("input", (e) => {
  clearSuggestion();
  //Convert input value to regex since string.startsWith() is case sensitive
  let regex = new RegExp("^" + input.value, "i");
  //loop through words array
  for (let i in words) {
    //check if input matches with any word in words array
    if (regex.test(words[i]) && input.value != "") {
      //Change case of word in words array according to user input
      words[i] = caseCheck(words[i]);
      //display suggestion
      suggestion.innerHTML = words[i];
      break;
    }
  }
});

//Complete predictive text on enter key
input.addEventListener("keydown", (e) => {
  //When user presses enter and suggestion exists
  if (e.keyCode == enterKey && suggestion.innerText != "") {
    e.preventDefault();
    input.value = suggestion.innerText;
    //clear the suggestion
    clearSuggestion();
  }
});

100+ JavaScript Projects With Source Code ( Beginners to Advanced)

Final Output


We have Successfully created our Autocomplete on Input Field using HTML, CSS & JavaScript (Source Code). You can use this project for your personal needs and the respective lines of code are given with the code pen link mentioned above.

If you find out this Blog helpful, then make sure to search code with random on google for Front End Projects with Source codes and make sure to Follow the Code with Random Instagram page.

Code Idea – codingartist

Written By – Harsh Sawant

Code By – @harshh9



Leave a Reply