Create a JavaScript Search box for a website

Create a Javascript Search Box in 5 Minutes

Rate this article

Share this article

JavaScript search box is a search box that can be added by adding a simple search box and a div to any website. If it can be done without any code adjustments, it makes the deal all the juicier. It should also have basic search features such as auto suggest, spell correct, search features, and more. Most JavaScript codes available on the internet give basic codes on how to add a JS search box, but the search box hardly is functional and usable for your website users.

You can create a JavaScript search box on the webpage and the users can search your page content with their keywords; it’s easy to use and very fast. We will discuss different methods of creating a JavaScript search box.

Create a JavaScript Search box for a website

JavaScript search box using ExpertRec

Before starting out to make a JavaScript search box using ExpertRec, make sure that is your website is live and not behind a login (you can add a search box for pages behind a login ). Have your sitemap URL handy. Also, make sure you have code access to your website. Follow the below steps

  1. Go to
  2. Login with your Gmail id. (SSO is enabled).
  3. Enter your website URL. (enter your website URL in the format https://www.yourwebsite.som).
  4. Enter your sitemap URL. ( if you don’t have a sitemap, you can leave this empty).
  5. Initiate a website crawl. (Now ExpertRec crawlers will start crawling your website. This could take some time depending on the size and number of pages on your website). If in case your crawl is stuck, drop an email to or use the ticketing feature to raise a support ticket).
  6. While the crawl is running, you can make changes to your search engine’s look and feel and also to the search engine’s ranking algorithm by using the control panel. There are more advanced features like search weights, promotions, synonyms, and more.
  7. Search weights let you tinker with the search ranking algorithm. You can give weights to different portions of the search engine results such as title, meta-description, URL, and more. This is a good way to do A/B testing for different search weights and find out which version gives the best conversion rates or sales.
  8. Once the crawl completes, check out your demo. Play around with the search engine, try different search queries to see if it suits your website content.
  9. Voice search is something that ExpertRec offers in chrome browsers. We will be rolling it out in other browsers such as Firefox and opera when the browsers start supporting voice search.
  10. If you would like to change the search engine ranking algorithm, you can do so by editing the weights of the search engine. In the search engine weights section, you can assign weights to portions of your search engine such as the URL, title, description, and others.
  11. Go to the code section and add it to your website. You can also email the code to your developer and ask him to add it to your website
    • the code contains two portions ( one within <script></script> and another piece of code <ci-search></ci-search>).
    • The <script></script> is just the JavaScript component and can be added using Google tag manager or using the code editor.
    • The <ci-search></ci-search> code adds the search box to your website. The place where you add this code determines the location of the search box.
  12. It is advisable to make the code changes in a test mode or development website before taking live in your live/ production site.
  13. As a final step, remove any website cache that you might have.
  14. Now your site search engine is live. You can check out the search analytics after a few days of search engine usage to check out what users are searching for and reorganize your content strategy accordingly.

Create a Javascript Search Box in 5 Minutes

Insert ExpertRec Search Engine HTML Code into your website

JavaScript Search Box from Scratch:

Creating your search form

<!-- Insert the below snippet where you want your searchbox to appear -->
<form method="get" action="">
<input type="text" name="search" id="search" value="" />
<input type="submit" name="submit" value="Search" />

Through JavaScript add the event handlers

// Insert the below snippet in your javascript, either inside <script> tag or in separate javascript file.
var defaultText = "Search...";
var searchBox = document.getElementById("search"); //default text after load
searchBox.value = defaultText;
//on focus behaviour
searchBox.onfocus = function() {
if (this.value == defaultText) {
//clear text field
this.value = '';
//on blur behaviour
searchBox.onblur = function() {
if (this.value == "") {
//restore default text
this.value = defaultText;
view raw search.js hosted with ❤ by GitHub

This will create a JavaScript search box on the webpage as :
javascript search box

JavaScript search box using Duckduckgo

javascript search box

To add a JavaScript search box using duckduckgo go here.

  1. Enter your website URL,
  2. choose a width in px,
  3. choose a background color.
  4. Enter the website URL you want to search for. If you have multiple URLs, enter each website separated by a comma.
  5. Enter a placeholder value (for example, search my website).
  6. Set Autofocus to on or off. (If On, the cursor will automatically be in the search box when the page loads)
  7. You can change DuckDuckGo settings via URL parameters by adding them after the search query, for example:


    These parameters are intended for individual use. They can also be used along with the site search to customize results pages more closely to your site. However, if using them for that purpose or any other beyond individual use (e.g. for apps/extensions), please do not remove the branding (ko, kr params, etc.) or advertising (k1, k4 params, etc.) as we have contracts in place that we would be violating if you did so. You can find more URL parameters here

Snippet to add duckduckgo search to your website
Add the below snippet where you want to insert duckduckgo search in your website.
More info on
src=" expertrec&focus=yes"
view raw duckduckgo.html hosted with ❤ by GitHub


JavaScript search using Google custom search

javascript search box for website

Google custom search is probably one of the most popular methods of adding a JavaScript search box to your website. It comes with ads. Here are steps to create a Google custom search engine.

  1. Go to
  2. Sign in with your Gmail id (get one if you don’t have a Gmail id).
  3. Click on new search engine.
  4. Under the basics, tab enter the name of the search engine.
  5. Under the search engine description, give brief decryption about your search engine.
  6. Under search engine keywords, add keywords that describe your search engine (for SEO purposes).
  7. Under sites to search, enter the list of URLs you want to search.
  8. If in case you want to search the entire web, turn on the search the entire web option.
  9. You can restrict Pages using Knowledge Graph Entities.
  10. You can also restrict Pages using Types.
  11. Go to look and feel, choose a layout that suits your website, and click on save and get code.
  12. Under themes, you can also choose a theme for your search engine.
  13. Under the basics tab under edition, click on get code and add this to your website.
  14. Once you add it to your website, you must be able to see the Google custom search JavaScript box on your website.

JavaScript search box using Yandex site search

  1. Go to You can change the language based on your preference.
  2. Sign in with or create a Yandex account.
  3. Give a technical name for your search engine. This will help in identifying your search engine in later stages.
  4. Under the search area, add sites to search. Here you can enter a single URL or multiple URLs.
  5. Edit the search form design. You can also edit the search placeholder text from “Yandex” to whatever you want to. Here you can change the look and feel of the search box.
  6. Display results– You can choose to show the search results on a particular URL. If not, search results will be taken to Yandex.javascript search box
  7. You can also edit the main page properties.
  8. The search results feature helps in editing the number of search results to be shown  and edit the look and feel of the search results page
  9. Sort By- You can choose to edit sort search results by date or by relevance.
  10. Code- In the code section, you get the code that has to be added to your website to take live Yandex custom search. You can add it using Google tag manager or send it to your developer who will be able to add it to your website.
  11. Search query statistics– You can see the top search statistics on your website. You will also be able to see queries that resulted in zero searches. You can use this report`
  12. Synonyms– You can add search synonyms. For example, if no (or only a few) documents contain the word “marriage”, the search will offer documents with the word “wedding”. You can add your own synonyms to the search base characteristic of your site and users. In the left column, add the words in question, and in the right column insert the synonyms from the site pages. In this case, you will have to add marriage as a synonym for the word wedding. Usually, it is a good practice to refer to your search statistics for top search queries that didn’t have any results and try adding synonyms to such words.
  13. Constraints-This will add filters to your website for users to filter the search results (for example- PDF, image, etc). This feature will help people to filter search results by category. This is similar to the filter by the brand feature that you find on e-commerce websites.

Try Super Fast JS Search Box on your website

Build your JS Search Box on your Website 

If you are looking to build a simple search box that does search data from your database, then read on. There are three important pieces of code that you need. 

File: index.html

The code that displays the search box on the website and displays the result ( Frontend code index.html )

<!DOCTYPE html>
<html lang="en">
<div id="search-box-container">
<form action="backend.php" method="get">
<input type="text" name="search-query" id="search-query" placeholder="Search for book title">
<input type="submit" name="submit" value="Submit">
<div id="search-result-container">
<script src="" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="simple-search.js"></script>
view raw index.html hosted with ❤ by GitHub


File: database.sql

Actual database with the data set to show on the result, without the actual data, none of your code is useful.

-- This is the capture of the commands that you can execute in mysql shell / mysql commandline
-- create database
create database book_shop default character set utf8;
-- create user and password
create user 'shopadmin'@'localhost' identified by 'shopadmin1234!@#$';
-- grant privileges to the user
GRANT ALL PRIVILEGES ON * . * TO 'shopadmin'@'localhost';
-- if you get `access denied error` if you are loggedin as other than root,
-- so login as root and try the same
sudo mysql -u root
-- Now after login as root user, try giving privileges to the user
GRANT ALL PRIVILEGES ON * . * TO 'shopadmin'@'localhost';
-- Now login as shopadmin for rest of the tasks to be done.
mysql -u shopadmin -p
use book_shop;
create table books (
title varchar(255),
author varchar(255)
INSERT into books (title, author) VALUES
('Exploring C', 'Yashavant Kanetkar'),
('Object Oriented Programming with C++','Balagurusamy'),
('Introduction to algorithms','Thomas H Cormen'),
('Design of The Unix Operating System','Maurice J. Bach');
view raw database.sql hosted with ❤ by GitHub


File: simple-search.js

Code that grabs the search text and sends it to the server for getting the result, and once the result has arrived from the server displays it to the user. ( Frontend JS code)

* filename: simple-search.js
* description: This file contains the javascript for the simple ajax search using
* javascript.
$(function() {
console.log( "ready!" );
$( "#search-query" ).keyup(function() {
var q = $( "#search-query" ).val();
console.log( "Handler for keyup called. " + q );
url: "backend.php",
data: { q: q },
}).done(function(response) {
// clear the results div previous results.
$( "#search-result-container" ).html( "<ul></ul>" );
response.results.forEach(function(obj) {
$( "#search-result-container" ).append( "<li>"+obj.title+"</li>" );


File: backend.php

Code that talks to the database and fetches the results that match with the search keyword given by the user (backend / serverside code).

* Filename: backend.php
* Project: simple-js-search
* Description: Backend that does data query from database using like function
* for the simple-js-search plugin.
if ( ! $_GET['q'] ){
return ;
$q = $_GET['q'];
$servername = "localhost";
$username = "shopadmin";
$password = "shopadmin1234!@#$";
$dbname = "book_shop";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
//echo "Connected successfully";
// Select database
if ( ! mysqli_select_db($conn,$dbname) ) {
echo "Database select failed !!";
$query = "SELECT *
FROM books
WHERE title LIKE '%$q%'";
$results = mysqli_query($conn,$query);
//$result_arr = [];
if(mysqli_num_rows($results) > 0){
// Fetch result rows as an associative array
while($result_arr[] = mysqli_fetch_assoc($results));
// remove last empty entry.
// Set the status to success, since we got the results.
$response['status'] = 'success';
// Add results received from database to response.
$response['results'] = $result_arr;
} else {
$response['status'] = 'failed';
$response['results'] = $result_arr;
// add instruction for the browser to interpret correctly as JSON.
header('Content-Type: application/json');
echo json_encode($response);
view raw backend.php hosted with ❤ by GitHub

But I would strongly recommend you to go for one of the services mentioned above for adding a Search Box to your website, Creating a search feature may go very complex if your search is from different fields or columns and it becomes too complex if you want to search spanning multiple tables. Creating a search for a website may be a great engineering exercise for an individual, but it’s a very resource, time involved if you are a website owner and you want to have a sophisticated search for your website..

Add JS Search Box to your website in less than 5 minutes



Why is my Search Box not Working

If you or your customers are having difficulty typing in your search box, one of the most common issues is having too many plugins on your website. To fix this, uninstall each plugin, and use the search box after every uninstall to know the plugin affecting the search box.

Other factors that might also cause your search box not to work include:

  • If your cache is overloaded, it starts affecting some of your features. So, you should constantly clear your cache history.
  • When your ctfmon.exe stops running. Ctfmon.exe is a Microsoft process that controls the alternative user input and the office language bar.
  • Unresponsive Cortana. Cortana helps save time and focus attention on the most important thing.
  • When you have a corrupted MaCtfMonitor scheduled task. Suppose you are unable to type or use your search bar. In that case, it can be that the MsCtfMonitor scheduled task responsible for monitoring the TextServiceFramework system service related to text input is corrupted or starred. 

Why Search box is Important for E-commerce

Research has revealed that search boxes generate 50% of the total revenue for e-commerce stores. However, without a search box, you leave your customers the tedious task of checking each page for what they want, and that experience can make you lose prospective customers.

Here are some reasons why a search box is important for your e-commerce

  • It Increases the Conversion Rate of your Website Visits

It is more difficult for customers to purchase on your website when there is no search box to help them locate what they want to buy. A search box on your e-commerce store ensures that website visits are not just visits but leads to sales. With a search box, customers can search for whatever they want, and if they have one, it increases their chance of making a purchase.

  • It Improves the Usability of your Website.

Search box improves website usability. Usability measures the ease of use of a website or product. With a search box, customers can navigate your website without complexities, creating a user-friendly environment for them when using your website. In addition, a usable website has a higher chance of being ranked by search engines for visibility, which is paramount for every e-commerce store. 

  • The Search Box Helps you Know What Your Customers Want.

The search box is your customer telling you what they want from you. This helps you to know what to include in your stock and the products to prioritize. The search box can be your go-to strategy for production if you are producing or making your wholesale purchase. You only need to check the volume of requests for each product, which informs the quantity you will produce or purchase.

  • You Can Leverage the Search Box Feature for Marketing Strategies.

The search box feature can help you with the focus of your marketing strategies. The search box saves your customers’ search history to the database. The search history can help you devise a means for your marketing strategy if the search for a particular product is high. You know you will concentrate your marketing strategies more on that product.

Enhancing User Experience with JavaScript Search Boxes for Websites

In today’s fast-paced digital landscape, providing an efficient and user-friendly website experience is paramount. One key element contributing to an improved user experience is the search functionality. A well-implemented JavaScript search box can significantly enhance navigation, making it easier for visitors to find the information they seek. In this article, we’ll delve deeper into the nuances of JavaScript-powered search boxes and explore how they can elevate your website’s functionality.

The Power of Real-Time Search

JavaScript’s real-time search capabilities have revolutionized the way users interact with websites. Unlike traditional search boxes that require users to press the “Enter” key to initiate a search, JavaScript enables real-time updates as users type. This dynamic approach provides instant results, creating a more interactive and responsive experience. As users input their queries, the search box filters and displays relevant results, eliminating the need for multiple clicks and page reloads.

Customization for Seamless Integration

One of the significant advantages of using JavaScript for search boxes is the flexibility it offers in terms of customization. With a few lines of code, developers can tailor the search box’s appearance, behaviour, and functionality to align with the website’s design and user interface. From simple styling adjustments to advanced features like autocomplete suggestions, JavaScript allows for a seamless integration that complements the overall aesthetics of the website.

Autocomplete Suggestions for Efficient Navigation

Autocomplete suggestions are a game-changer when it comes to enhancing the search experience. By leveraging JavaScript, you can implement an autocomplete feature that predicts and displays potential search queries as users type. This not only accelerates the search process but also helps users discover relevant content more efficiently. Additionally, autocomplete suggestions reduce the likelihood of typos or misspelt queries, ensuring accurate and timely results.

Integration with Backend Services

JavaScript search boxes can be seamlessly integrated with backend services, enabling comprehensive search functionality. Whether your website relies on static content or dynamic data from a database, JavaScript can bridge the gap between the front end and back end, ensuring a robust search mechanism. This integration facilitates the retrieval of up-to-date information, making the search experience more reliable and comprehensive.

Responsive Design for Mobile Optimization

In an era where mobile devices dominate internet usage, ensuring a responsive design is crucial. JavaScript search boxes can be optimized for various screen sizes and resolutions, providing a consistent and user-friendly experience across devices. Mobile users can enjoy the same real-time search capabilities and customization options, ensuring that the website caters to the diverse preferences of its audience.

Best Practices for Implementing JavaScript Search Boxes

While JavaScript offers a plethora of possibilities for enhancing search boxes, it’s essential to adhere to best practices to ensure optimal performance and user satisfaction. Here are some key considerations:

  • Efficient Algorithm: Implement an efficient search algorithm to handle large datasets and deliver quick results.
  • Accessibility: Ensure that the search box is accessible to users with disabilities by incorporating proper ARIA roles and attributes.
  • Cross-Browser Compatibility: Test the search box across different browsers to guarantee a consistent experience for all users.
  • User Feedback: Provide clear and concise feedback to users, such as loading indicators or error messages, to enhance the overall transparency of the search process.

In conclusion, a well-implemented JavaScript search box is a valuable asset for any website aiming to prioritize user experience. By embracing real-time search, customization options, and seamless integrations, your website can stand out in the digital landscape, offering visitors a hassle-free and efficient way to discover the content they seek. So, go ahead, leverage the power of JavaScript, and elevate your website’s search functionality to new heights.

Add great search to your website

Are you showing the right products, to the right shoppers, at the right time? Contact us to know more.
You may also like