In today's digital age, user experience on the web is crucial to the success of any project. One of the features that significantly improves this experience in web forms is autocomplete. This functionality not only streamlines the data filling process, but also improves the accuracy of the information entered. In this guide I will show you how to implement an autocomplete system using only JavaScript, without depending on additional libraries.
Table of Contents
ToggleWhat is an AutoComplete Function?
Autocomplete is a user interface feature that predicts the rest of a word or phrase as the user begins typing in a form field. This not only speeds up data entry, but also helps avoid typing errors and improves usability.
Initial Steps: Preparing your Project
Before we dive into the code, make sure you have a suitable environment for development. You will need the following:
- Code Editor: You can use editors like VSCode or Sublime Text.
- Modern Browser: Chrome, Firefox or any browser that supports modern JavaScript.
- Development console: Accessible in most browsers to test and debug your code.
Once you have everything ready, create a new folder for your project and inside, a file called index.html
and another call script.js
.
Initial structure of your HTML
Next, we will build the basic structure of your file index.html
. Here is an initial example:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Autocomplete Form</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="autocomplete-container">
<input id="autocomplete-input" type="text" placeholder="Write something...">
</div>
<script src="script.js"></script>
</body>
</html>
Make sure the JS script is loaded at the end of the body so that all HTML content is available before the JavaScript tries to access it.
Implementing AutoComplete with JavaScript
Step 1: Create the Base Function
in your file script.js
, let's start by developing a function that listens to each key pressed in the input and starts filtering suggestions based on the user's input.
document.addEventListener('DOMContentLoaded', function() { const inputData = ["Apple", "Banana", "Cherry", "Date", "Fig", "Grape", "Lemon"]; const inputField = document .getElementById('autocomplete-input'); inputField.addEventListener('input', function() { let input = this.value; if (!input) { clearSuggestions(); return; } let suggestions = getMatches(inputData , input); showSuggestions(suggestions, this); function getMatches(data, input) { let matches = []; let regex = new RegExp(`${input}`, 'i'); // 'i' to ignore case for (let i = 0; i < data.length; i++) { if (data[i].match(regex)) { matches.push(data[i]); } } return matches; }
Step 2: Show Suggestions
The function display suggestions()
will manipulate the DOM to display the possible hints under the input field:
function showSuggestions(suggestions, inputField) { clearSuggestions(); let suggestionBox = document.createElement('div'); suggestionBox.id = 'suggestion-box'; inputField.parentNode.appendChild(suggestionBox); suggestions.forEach(function(item) { let div = document.createElement('div'); div.innerHTML = item; div.addEventListener('click', function() { inputField.value = this.innerText; clearSuggestions (); }); suggestionBox.appendChild(div); } function clearSuggestions() { const existingBox = document.getElementById('suggestion-box'); if (existingBox) { existingBox.parentNode.removeChild(existingBox); } }
Step 3: Styling AutoFill
Add the file styles.css
to visually enhance suggestions and ensure users have a good visual and functional experience.
.autocomplete-container { position: relative; width: 300px; margin: 0 self; } #suggestion-box { position: absolute; background: white; width: 100%; border: 1px solid #ccc; } #suggestion-box div { padding: 8px; cursor: pointer; } #suggestion-box div:hover { background-color: #f0f0f0; }
Conclusion
Implementing an autocomplete function in your web forms may seem complex, but with a little JavaScript, it is perfectly possible to do it without dependency on external libraries. Now that you have a basic autocomplete feature, you can adapt and enhance it to fit the specific needs of your web projects.
If you want to delve deeper into JavaScript or have any questions, feel free to visit my blog or contact me through my contact page. I'm here to help you on your path to web development mastery.
Happy coding!