DEV Community

Cover image for ๐Ÿ‘จโ€๐Ÿ’ป Make AutoComplete Input Box In Pure Javascript ๐Ÿ”ฅ๐Ÿ”ฅ
Kushal sharma
Kushal sharma

Posted on

๐Ÿ‘จโ€๐Ÿ’ป Make AutoComplete Input Box In Pure Javascript ๐Ÿ”ฅ๐Ÿ”ฅ

Hi folks, I hope that you are doing well and are trying to learn some new things during this quarantine. I have started to write a blog with all the free time I have; due to the lockdown in India.

So, in this post, we are going to learn how to code a simple search with autocomplete functionality (like Google shows while you search for some stuff). We are not going to deal with the backend for this one. I will write another blog for that. So let's get started...

Below is an example of what we are going to build

First, we type the HTML for the simple app as follows:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
   <link rel="stylesheet" href="index.css"/>
</head>
<body>
   <div class="container">
        <div class="search-container">
           <input type="text" onkeyup="filterNames(event)">
       </div>
       <ul class="list-container" id ="list-container">
           <li>Kushal Sharma</li>
       </ul>
   </div>
</body>
<script src="index.js"></script>
</html>

Now, let's style the app with a little bit of CSS:

*{
   box-sizing: border-box;
   margin: 0px;
   padding: 0px;
}
.container{
   margin-top: 25px;
   margin-left:auto;
   margin-right: auto;
   min-height: 500px;
   width: 80%;
   border: 1px solid black;
}
.search-container{
   width: 100%;
}
.search-container input{
   width: 100%;
   height: 40px;
   font-size: 25px;
}

.list-container li{
   list-style: none;
   border: 1px solid red;
   padding: 15px 15px;
   font-size: 25px;
}

Now our app looks like this:

Alt Text

This very little amount of styling is ok to accomplish the autocomplete functionality. Now for the process of the autocomplete; we need to filter the records that match with our typed character. To do that we are going to store those records in an array with JSON.

Next, let's make a new file saved as index.js and type the following code:

const names = [
   {
       name:"kushal sharma",
   },
   {
       name:"Jeremy",
   },
   {
       name:"john",
   },
   {
       name:"sandeep",
   },
   {
       name:"mohit",
   },
   {
       name:"sanjeev",
   },
   {
       name:"maininder",
   },
   {
       name:"Ajay",
   }
]

(A simple array literal such as ' name = [โ€œkushalโ€,โ€jeremyโ€,โ€johnโ€,โ€sachinโ€] ' could work too, but I prefer to use JSON).

When we open our index.html file, we want the names to display so we can filter among them. To do this we need to make each name into an HTML DOM element. We will use a function to convert our names into DOM elements and display them on the UI like this:

function renderNames(arrayOfNames) {
   let liElemet = "" ;
   for (let i= 0; i <arrayOfNames.length; i++) {
   liElemet += `<li>${arrayOfNames[i].name}</li>`
   }
   document.getElementById("list-container").innerHTML= liElemet;
}

So here we made a function renderNames that accepts the arrayOfNames argument which consists of the array of names we created previously.

On this line of code, we are making a list

  • element and writing the names one by one inside of the element.
    liElemet += `<li>${arrayOfNames[i].name}</li>`
    

    Once we make all the

  • elements of names we are telling the javascript to add all these as the child of list-container which is an unordered list
      element.

      Now, we need to invoke this function by passing it the array of names like this:

    renderNames(names);
    

    Now we can see the List of all of our names:

    Alt Text

    Next, we will work on the main functionality. First, we need to catch what we are typing. For this, we will use the HTML events with JavaScript code. Whenever a change happens in the browser window is an event. If you press a key, it is an event. Moving the mouse and resizing your window is also an event. So we need to deal with the keyboard keypress event since we are conducting a search.

    <input type="text" onkeyup="filterNames(event)">
    

    Here we have added the onkeyup attribute and it calls the filterNames() function and passes the event as an argument. The event argument contains all the information about the event, from where it has fired, what the target element is, what the value is, etc.

    So letโ€™s create the filterNames() function:

    function filterNames(event) {
       var searchvalue = event.target.value;
       var filterNames = names.filter((v,i)=>{
           return(v.name.includes(searchvalue));
       })
       renderNames(filterNames);
    }
    

    Inside the filterNames() function we are catching which key is pressed using " event.target.value " and then we are filtering through the names of the array and returning only those names which included the typed character. And then again, invoking the renderNames() function with the new array of names returned by the filter() method.

    Alt Text

    Now you can see in the search example, as I typed the characters "sa" two names were returned "sandeep" and "sanjeev" which both contain the characters "sa" in it.

    Hooray! We have made a search with autocomplete functionality in pure JavaScript!

    I hope you liked this one, and if you have any questions write them down in the comments. Follow me on twitter โ‡’ Twitter to see what I am working on daily.

    And you can also follow me on Dev to notified when I published a new blog

  • Discussion (24)

    Collapse
    manikantapamarthi profile image
    Manikanta Nagaraju Pamarthi

    I think your just filtering the names array, How to select the name from the list?

    Collapse
    sharmakushal profile image
    Kushal sharma Author

    You can easily do this by adding the onclick function to the li element and getting its index and get the respective value from the array for that index and saving to your variable

    Collapse
    xuchunyang profile image
    ๅพๆ˜ฅ้˜ณ

    Selecting with mouse seems easy. Most autocomplete interface supports keyboard up/down arrow keys, we need maintain the current selection state somewhere, it does not seem easy to me (I'm a beginner to webdev).

    Collapse
    manikantapamarthi profile image
    Manikanta Nagaraju Pamarthi

    Yes, I tried with some dynamic data coming from the DB, but on click, is not working. May be because of element rendering problem.

    anyhow I fixed my problem in my own way.

    Thank you.

    Collapse
    dailydevtips1 profile image
    Chris Bongers

    Nice one, also think about using a datalist, better support and easier in a sense for what you are demo'ing

    Collapse
    jeromehardaway profile image
    Jerome Hardaway

    Nice.

    Collapse
    sharmakushal profile image
    Kushal sharma Author

    thanx for reading

    Collapse
    andreluis7 profile image
    andreluis7

    Very nice Kushal!

    Collapse
    sharmakushal profile image
    Kushal sharma Author

    thanks for reading

    Collapse
    andrewbaisden profile image
    Andrew Baisden

    Very cool and easy to implement in projects.

    Collapse
    sharmakushal profile image
    Kushal sharma Author

    thanks for reading

    Collapse
    djdev profile image
    Deepjyoti Rajkhowa

    Nice work. Additionally it would be nice to have it work without being case-sensitive.

    Collapse
    juanduquemkt profile image
    Juan Duque

    Great!!

    Collapse
    sharmakushal profile image
    Kushal sharma Author

    thnx for reading

    Collapse
    patarapolw profile image
    Pacharapol Withayasakpunt

    What does pure JavaScript mean anyway? No HTML, no CSS, no C++, no node-gyp?

    Collapse
    sharmakushal profile image
    Kushal sharma Author

    Means that without the use of any library like the react, vue or any framework

    Collapse
    joaovmvini profile image
    joaovmvini

    Nice article, thanks for sharing! I have build a javascript dropdown plugin, check it out: jsuites.net/v3/dropdown-and-autoco...

    Collapse
    rwbeast profile image
    rwbeast

    nice clickbait! ( look at the thumbnail )

    Collapse
    sharmakushal profile image
    Kushal sharma Author

    I get only this image on google for autosuggest

    Collapse
    rwbeast profile image
    rwbeast

    you could use screenshot of your own example

    Thread Thread
    sharmakushal profile image
    Kushal sharma Author

    i tried to make a gif , i also looked for any s/w as i working on the linux i can't find any realted s/w so used this one

    Thread Thread
    rwbeast profile image
    rwbeast

    Bro I use linux ( Ubuntu ) too. you can use "VokoScreen" app for recording your screen

    Thread Thread
    sharmakushal profile image
    Kushal sharma Author

    thnx I will use this one for the next time

    Thread Thread
    rwbeast profile image
    rwbeast

    JAI BHARAT!