Welcome to our comprehensive guide on creating an Autocomplete Search using jQuery! This tutorial is designed for both beginners and intermediate learners. Let's dive right in!
Autocomplete Search is a user-friendly feature that suggests possible search terms as you type. It's a handy tool for improving user experience on websites, especially those with extensive data or lengthy search queries.
First, let's set up our project. We'll need:
Here's a basic HTML structure for our search box:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ... -->
</head>
<body>
<div id="search-box">
<input type="text" id="search-input" />
<ul id="search-results"></ul>
</div>
<!-- ... -->
<script src="jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>Our JSON data will be used to populate the autocomplete suggestions. Here's an example:
[
{
"id": 1,
"name": "Example One"
},
{
"id": 2,
"name": "Example Two"
},
<!-- ... -->
]Now, let's write the jQuery code to handle the autocomplete search:
$(document).ready(function() {
// Load JSON data
var data = [];
$.getJSON('data.json', function(json) {
data = json;
// Initialize autocomplete
initAutocomplete();
});
function initAutocomplete() {
// On input change, search for matches
$('#search-input').on('input', function() {
var userInput = $(this).val().toLowerCase();
var suggestions = [];
// Filter data and create suggestions
$.each(data, function(index, item) {
if (item.name.toLowerCase().indexOf(userInput) !== -1) {
suggestions.push(item);
}
});
// Display suggestions
$('#search-results').empty();
$.each(suggestions, function(index, item) {
var li = $('<li></li>').text(item.name);
$('#search-results').append(li);
});
});
}
});💡 Pro Tip: You can customize the appearance of the suggestions by styling the #search-results CSS selector.
Now, save your HTML, JavaScript, and JSON files in the same folder. Open the HTML file in a web browser, and you should see a search box with an autocomplete feature!
Which of the following files contains our data?
That's it for our Autocomplete Search tutorial! As you practice, you'll be able to create more advanced features and improve your jQuery skills. Happy coding! 🎉