jQuery Autocomplete Search Tutorial 🎯

beginner
8 min

jQuery Autocomplete Search Tutorial 🎯

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!

What is Autocomplete Search? 📝

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.

Setting Up the Project 💡

First, let's set up our project. We'll need:

  1. An HTML file for our webpage structure
  2. A JavaScript file for our jQuery code
  3. A JSON file containing our data

HTML Structure 📝

Here's a basic HTML structure for our search box:

html
<!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>

JSON Data 📝

Our JSON data will be used to populate the autocomplete suggestions. Here's an example:

json
[ { "id": 1, "name": "Example One" }, { "id": 2, "name": "Example Two" }, <!-- ... --> ]

jQuery Code 💡

Now, let's write the jQuery code to handle the autocomplete search:

javascript
$(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.

Putting It All Together ✅

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!

Quiz 🎯

Quick Quiz
Question 1 of 1

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! 🎉