Hello readers, Today in this blog you’ll learn how to create a Simple Search Bar with Autocomplete Search Suggestions using HTML CSS & JavaScript. Earlier I shared a blog on how to create an Animated Search Bar using only HTML & CSS and now it’s time to create an Autocomplete Textbox or Search box.
A search box is a graphical UI element present in many websites. It works as the field for a query input or search term from the user to search and retrieve related information from the database. Autocomplete is a pattern or feature used to display query suggestions and predict the rest of a word a user is typing.
In this program [Search Bar with Auto-complete Search Suggestions], on the webpage, there is a search bar and when you type something, there is shown an autocomplete box that suggests several predictions of how your query could be completed means there are several suggestions related your query. If you’re finding it difficult to understand what I am saying. You can watch a full video tutorial on this program [Autocomplete Search Bar].
Video Tutorial of Search Bar with Autocomplete Search
In the video, you have seen the Search Bar with Autocomplete Search Suggestions and there is no content-related user query so I redirected the user query to Google but you can show your content and I hope you have understood the basic codes or concepts behind creating this autocomplete textbox or search box.
You might like this:
Search Bar with Auto-complete Search [Source Codes]
To create this program (Autocomplete Search Suggestions). First, you need to create four Files one HTML File, CSS File and two are JavaScript Files. After creating these files just paste the following codes into your file.
First, create an HTML file with the name of index.html and paste the given codes in your HTML file. Remember, you’ve to create a file with .html extension.
<!DOCTYPE html> <!-- Created By CodingNepal - www.codingnepalweb.com --> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Autocomplete Search Box | CodingNepal</title> <link rel="stylesheet" href="style.css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/> </head> <body> <div class="wrapper"> <div class="search-input"> <a href="" target="_blank" hidden></a> <input type="text" placeholder="Type to search.."> <div class="autocom-box"> <!-- here list are inserted from javascript --> </div> <div class="icon"><i class="fas fa-search"></i></div> </div> </div> <script src="js/suggestions.js"></script> <script src="js/script.js"></script> </body> </html>
Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap'); *{ margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } body{ background: #644bff; padding: 0 20px; } ::selection{ color: #fff; background: #664AFF; } .wrapper{ max-width: 450px; margin: 150px auto; } .wrapper .search-input{ background: #fff; width: 100%; border-radius: 5px; position: relative; box-shadow: 0px 1px 5px 3px rgba(0,0,0,0.12); } .search-input input{ height: 55px; width: 100%; outline: none; border: none; border-radius: 5px; padding: 0 60px 0 20px; font-size: 18px; box-shadow: 0px 1px 5px rgba(0,0,0,0.1); } .search-input.active input{ border-radius: 5px 5px 0 0; } .search-input .autocom-box{ padding: 0; opacity: 0; pointer-events: none; max-height: 280px; overflow-y: auto; } .search-input.active .autocom-box{ padding: 10px 8px; opacity: 1; pointer-events: auto; } .autocom-box li{ list-style: none; padding: 8px 12px; display: none; width: 100%; cursor: default; border-radius: 3px; } .search-input.active .autocom-box li{ display: block; } .autocom-box li:hover{ background: #efefef; } .search-input .icon{ position: absolute; right: 0px; top: 0px; height: 55px; width: 55px; text-align: center; line-height: 55px; font-size: 20px; color: #644bff; cursor: pointer; }
Third, create a JavaScript file with the name suggestions.js and paste the given codes into your JavaScript file. Remember, you’ve to create a file with .js extension. We create this file to store all suggestion keywords.
let suggestions = [ "Channel", "CodingLab", "CodingNepal", "YouTube", "YouTuber", "YouTube Channel", "Blogger", "Bollywood", "Vlogger", "Vechiles", "Facebook", "Freelancer", "Facebook Page", "Designer", "Developer", "Web Designer", "Web Developer", "Login Form in HTML & CSS", "How to learn HTML & CSS", "How to learn JavaScript", "How to became Freelancer", "How to became Web Designer", "How to start Gaming Channel", "How to start YouTube Channel", "What does HTML stands for?", "What does CSS stands for?", ];
Last, create a JavaScript file with the name of script.js and paste the given codes in your JavaScript file. Remember, you’ve to create a file with .js extension.
// getting all required elements const searchWrapper = document.querySelector(".search-input"); const inputBox = searchWrapper.querySelector("input"); const suggBox = searchWrapper.querySelector(".autocom-box"); const icon = searchWrapper.querySelector(".icon"); let linkTag = searchWrapper.querySelector("a"); let webLink; // if user press any key and release inputBox.onkeyup = (e) => { let userData = e.target.value; //user enetered data let emptyArray = []; if (userData) { icon.onclick = () => { webLink = `https://www.google.com/search?q=${userData}`; linkTag.setAttribute("href", webLink); linkTag.click(); } emptyArray = suggestions.filter((data) => { //filtering array value and user characters to lowercase and return only those words which are start with user enetered chars return data.toLocaleLowerCase().startsWith(userData.toLocaleLowerCase()); }); emptyArray = emptyArray.map((data) => { // passing return data inside li tag return data = `<li>${data}</li>`; }); searchWrapper.classList.add("active"); //show autocomplete box showSuggestions(emptyArray); let allList = suggBox.querySelectorAll("li"); for (let i = 0; i < allList.length; i++) { //adding onclick attribute in all li tag allList[i].setAttribute("onclick", "select(this)"); } } else { searchWrapper.classList.remove("active"); //hide autocomplete box } } function select(element) { let selectData = element.textContent; inputBox.value = selectData; icon.onclick = () => { webLink = `https://www.google.com/search?q=${selectData}`; linkTag.setAttribute("href", webLink); linkTag.click(); } searchWrapper.classList.remove("active"); } function showSuggestions(list) { let listData; if (!list.length) { userValue = inputBox.value; listData = `<li>${userValue}</li>`; } else { listData = list.join(''); } suggBox.innerHTML = listData; }
That’s all, now you’ve successfully created a Search Bar with Autocomplete Search Suggestions in JavaScript. If your code does not work or you’ve faced any error/problem, please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it.
Hello, how can I search within the site
Thank you so much for creating this! It is so close to what I need for my site. However, instead of all suggestions (I’m replacing them with locations), linking to a google search for that suggestion keyword, I need them to open up a box with information about that location just below the search bar itself. What part of your code do I change and what do I change it to?
Currently, I’m using this script to toggle open and closed an info box below the search bar I have. Here is that code.
document.querySelectorAll(“.collapsible”).forEach(function(current) {
let toggler = document.createElement(“div”);
toggler.className = “toggler”;
current.appendChild(toggler);
toggler.addEventListener(“click”, function(e) {
current.classList.toggle(“open”);
}, false);
});
But because this uses li elements, I have to list all the locations (there are 64 of them) on the page. That makes for a very long page and if I display: none; to hide them, my search box no longer functions.
So, to be clear, I want to use your search box because I don’t have to list all of the suggestions below it, but I want the chosen selection to toggle open a box with data I’ve compiled either in the same html page or else as an anchor in another html file on my site. Hope that made sense.
thanks again
Nice…
Bro how to make suggestions of another pages code at the bottom of website
It can be open in folder alsoo???
Create Program and easy to follow tutorial.
I was wondering how you would limit the search results to just 3 or 4 items rather than all partially matching ones?
Hi, I want to make a search bar that would send people to other sites of my website, so I put my domain name instead of google.com in the script but let’s say that I have sites that are not single words, but like 2 or 3 words, and when you do SPACE there is % by default, and I’m using dash (-) in naming my files, is there any way to do it?
Example:
mydomain.com <— that's my domain name
Now someone is looking for "Car parts" on my website, so I want search bar to send him to:
mydomain.com/car-parts
But this search bar is sending to:
mydomain.com/car%parts
And it's not working, any ideas how to solve this?
Good for the job boy
Search suggestions do not work up and down the keyboard key
You have to add codes for that!
Fantastic post, Thanks CodingNepal
can you provide me with example for me if i want to connect the search to a google form link of specific names of people, will be of great help.
Hi, thanks for the instructions, can you provide me with example for me if i want to connect the search to a google form link of specific names of people, will be of great help.
Hello, if I want each suggestion to take me to a different page, how do I do it?
Hi, thanks for the instructions, can you provide me a simple code for me if i want to connect the search to a google form link of specific names of people, will be of great help.
What to do if i want to fetch data from an api and use search bar to like search any stock name and would get it’s price with the help of that api
How to i use this codes for my blogger site? Please make a video
HI, thanks for the video but is it possible ton change the link to the website to a link to another page of the site ?
Is it possible to add the file suggestions (dynamically). That means, I have a list of files in my computer system, and I wanted to make it searchable via script in my html. If its possible, please suggest me the way. I got some permission error.
Both Search Bar work for different work.
Sir, How can we add two search bar on same page or on 1 page.
please Help.
@CodingNepal where we have to paste the last function codes?
I didn’t understand
Hi CodingNepal can you combine this video with you Animated Search Box using HTML CSS & JavaScript | Elastic Animation on Search Bar because I am having trouble merging then because I am a beginner
Hi CodingNepal! I love your content.. Can i have an example of that search bar with link when you clicked a suggestion? Pls post it on youtube… thanks!
Okay, I’ll try to upload a video on it.
Hi, what can I change to only show the first 5 or so results? Maybe adding a [:5] after some array? Thanks!!
Sorry, I can’t comment codes here. Please view this screenshot and replace the last function codes of the script.js file with this one- https://www.codingnepalweb.com/wp-content/uploads/2021/06/suggestion-list-js-viewer-comment.jpg
Thank You for this.
But please can you tell me how can I make this responsive
You can add only one redirection link in all li tags because I did not code for it but I'll make separate video for it.
hi thanks for the code, can you explain with an example where I can put a link to the suggestion
You may offline
I'll try to make video on it
Can you show me how to get a link ps I don't know anything about JavaScript.
I got an error on that. It says: Failed to load resource: net::ERR_FILE_NOT_FOUND
Is there any help for that?
Please contact me on Instagram and send me the screenshot of the error.
When I add this to my website, i couldn't select the suggestion. And this error appear
"Uncaught ReferenceError: select is not defined
at HTMLLIElement.onclick (contact.html:1)". Please help me!
Yes I have provided Zip file also…You may forgot to read the blog.
Great content it looks like am trapped here but make sure to provide zip files to save us from the tiresome copy and paste!
You're most welcome 🙂
inside each li just add anchor tag
Thank You for making it free
How to i use this codes for blogger site? Please make a video with this topic
can u explain how to add link to search bar?
inside each li just add anchor tag
how do i add links to the items in suggestions list
Contact me on Email and visit our contact or about page for email address.
Hi dear i want to make a website from you i am your biggest fan thanks 🙂
You mean on suggestions list
bro please tell what to do if we have to insert the link for particular search.
bro please tell what to do if we have to insert the link for particular search.
Ok I'll make video tutorial on it otherwise you can download magify template.
hi, codingNepal Can you share the code of your footer because I like its design.