Search Input with Suggestions

Building a Dynamic Search Input with Suggestions: A Step-by-Step Guide


In the dynamic landscape of web development, creating an efficient and user-friendly search functionality is paramount. In this tutorial, we’ll delve into the process of building a dynamic search input with suggestions using HTML, CSS, and JavaScript. Whether you’re a beginner looking to enhance your skills or an experienced developer seeking a refresher, this step-by-step guide will walk you through the code and its functionalities.

Prerequisites

Before we begin, ensure that you have a basic understanding of HTML, CSS, and JavaScript. Additionally, you’ll need a text editor to write and test your code.

Setting Up the HTML Structure

Let’s start by laying the foundation for our search input. We’ll create a clean and organized HTML structure to house our search bar and suggestions.


<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">  
<title>CodePen - Building a Dynamic Search Input with Suggestions: A Step-by-Step Guide</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">

<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
  
</head>

<body translate="no">
 
<div class="search-wrapper">
    <div class="search-input">
      <input type="text" placeholder="Type to search..." id="searchInput">
      <div id="suggestions">
        <a href="#">Khushal</a>
        <a href="#">Vishal</a>
        <a href="#">Hiren</a>
        <a href="#">Jaydip</a>
        <a href="#">Abhay</a>
        <a href="#">Bhavik</a>
        <a href="#">Darsh</a>
        <a href="#">Mayur</a>
      </div>
      <div class="search-icon"><i class="fas fa-search"></i></div>
      <div class="error-message" id="errorMessage">No matching suggestion found</div>
      <div class="cancel-button" id="cancelButton"><i class="fas fa-times-circle"></i></div>
    </div>
  </div>


</body>
</html>

Styling with CSS

A visually appealing design is crucial for a positive user experience. Learn how to style the search input, suggestions, and error messages with CSS.


<style>
/* Add your styles here */
.search-wrapper {
margin: 50px;  
}

.search-input {
position: relative;
max-width: 300px;
margin: auto; 
}

input[type="text"] {
width: calc(100% - 32px);
padding: 8px;
padding-left: 35px;
outline: none;
border: 2px solid #ccc;
border-radius: 50px;
}

input[type="text"]:focus {
border: 2px solid  rgb(146, 146, 146) !important;
}

#suggestions {
list-style: none;
padding: 0;
display: none;
position: absolute;
background-color: white;
width: 100%;
border: 1px solid #ccc;
z-index: 1;
}

#suggestions a {
display: block;
padding: 8px;
border-bottom: 1px solid #eee;
text-decoration: none;
color: #333;
}

#suggestions a:last-child {
border-bottom: none;
}

input::placeholder {
color: rgb(146, 146, 146);
}

.error-message {
display: none;
color: red;
margin-top: 5px;
}

.cancel-button {
position: absolute;
top: 19px;
right: 0px;
transform: translateY(-50%);
cursor: pointer;
display: none;
}
.search-icon{
position: absolute;
top: 8px;
left: 10px;
}
</style>

Implementing Dynamic Search with JavaScript

Now comes the exciting part – implementing dynamic search functionality. We’ll use JavaScript to filter suggestions based on user input, display relevant matches, and handle errors gracefully.

Enhancing User Interaction

To provide a seamless experience, we’ll add a cancel button for users to reset the search input easily. Learn how to improve user interaction and responsiveness.

<script id="rendered-js" >
const searchInput = document.getElementById('searchInput');
const suggestionsList = document.getElementById('suggestions');
const errorMessage = document.getElementById('errorMessage');
const cancelButton = document.getElementById('cancelButton');

searchInput.addEventListener('input', function () {
const inputValue = this.value.trim().toLowerCase();
const suggestionItems = suggestionsList.querySelectorAll('a');

let hasMatches = false;

suggestionItems.forEach(function (listItem) {
const textValue = listItem.textContent.toLowerCase();
const displayStyle = textValue.includes(inputValue) ? 'block' : 'none';
listItem.style.display = displayStyle;
hasMatches = hasMatches || displayStyle === 'block';
});

suggestionsList.style.display = hasMatches ? 'block' : 'none';
errorMessage.style.display = hasMatches || inputValue.length === 0 ? 'none' : 'block';
cancelButton.style.display = inputValue.length > 0 ? 'block' : 'none';
});

cancelButton.addEventListener('click', function () {
searchInput.value = '';
suggestionsList.style.display = 'none';
errorMessage.style.display = 'none';
cancelButton.style.display = 'none';
});
//# sourceURL=pen.js
</script>

Conclusion

Congratulations! You’ve successfully created a dynamic search input with suggestions. Recap the key concepts covered in this tutorial and explore further enhancements or customization options for your search functionality.

Full Source Code


<!DOCTYPE html>
<html lang="en" >

<head>
<meta charset="UTF-8">
<meta name="apple-mobile-web-app-title" content="CodePen">
<title>CodePen - Building a Dynamic Search Input with Suggestions: A Step-by-Step Guide</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">

<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>

</head>

<style>
/* Add your styles here */
.search-wrapper {
margin: 50px;  
}

.search-input {
position: relative;
max-width: 300px;
margin: auto; 
}

input[type="text"] {
width: calc(100% - 32px);
padding: 8px;
padding-left: 35px;
outline: none;
border: 2px solid #ccc;
border-radius: 50px;
}

input[type="text"]:focus {
border: 2px solid  rgb(146, 146, 146) !important;
}

#suggestions {
list-style: none;
padding: 0;
display: none;
position: absolute;
background-color: white;
width: 100%;
border: 1px solid #ccc;
z-index: 1;
}

#suggestions a {
display: block;
padding: 8px;
border-bottom: 1px solid #eee;
text-decoration: none;
color: #333;
}

#suggestions a:last-child {
border-bottom: none;
}

input::placeholder {
color: rgb(146, 146, 146);
}

.error-message {
display: none;
color: red;
margin-top: 5px;
}

.cancel-button {
position: absolute;
top: 19px;
right: 0px;
transform: translateY(-50%);
cursor: pointer;
display: none;
}
.search-icon{
position: absolute;
top: 8px;
left: 10px;
}
</style>


<body translate="no">

<div class="search-wrapper">
<div class="search-input">
<input type="text" placeholder="Type to search..." id="searchInput">
<div id="suggestions">
<a href="#">Khushal</a>
<a href="#">Vishal</a>
<a href="#">Hiren</a>
<a href="#">Jaydip</a>
<a href="#">Abhay</a>
<a href="#">Bhavik</a>
<a href="#">Darsh</a>
<a href="#">Mayur</a>
</div>
<div class="search-icon"><i class="fas fa-search"></i></div>
<div class="error-message" id="errorMessage">No matching suggestion found</div>
<div class="cancel-button" id="cancelButton"><i class="fas fa-times-circle"></i></div>
</div>
</div>

<script id="rendered-js" >
const searchInput = document.getElementById('searchInput');
const suggestionsList = document.getElementById('suggestions');
const errorMessage = document.getElementById('errorMessage');
const cancelButton = document.getElementById('cancelButton');

searchInput.addEventListener('input', function () {
const inputValue = this.value.trim().toLowerCase();
const suggestionItems = suggestionsList.querySelectorAll('a');

let hasMatches = false;

suggestionItems.forEach(function (listItem) {
const textValue = listItem.textContent.toLowerCase();
const displayStyle = textValue.includes(inputValue) ? 'block' : 'none';
listItem.style.display = displayStyle;
hasMatches = hasMatches || displayStyle === 'block';
});

suggestionsList.style.display = hasMatches ? 'block' : 'none';
errorMessage.style.display = hasMatches || inputValue.length === 0 ? 'none' : 'block';
cancelButton.style.display = inputValue.length > 0 ? 'block' : 'none';
});

cancelButton.addEventListener('click', function () {
searchInput.value = '';
suggestionsList.style.display = 'none';
errorMessage.style.display = 'none';
cancelButton.style.display = 'none';
});
//# sourceURL=pen.js
</script>


</body>
</html>

Codepen

[codepen_embed height=”600″ default_tab=”html,result” slug_hash=”NWJRaKv” user=”mr__khushal”]See the Pen
Building a Dynamic Search Input with Suggestions: A Step-by-Step Guide
by khushal (@mr__khushal)
on CodePen.[/codepen_embed]


Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *