How to implement autocomplete functionality for a text input using jQuery



Image not found!!

Implementing autocomplete functionality for a text input using jQuery involves a combination of HTML, CSS, and JavaScript. Here's a step-by-step guide on how to achieve this:

  1. Include jQuery: Ensure you include the jQuery library in your HTML file. You can either download it and host it locally or include it from a CDN.

    html
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  2. HTML Structure: Create the HTML structure for your input field.

    html
    <input type="text" id="autocomplete-input" placeholder="Type something..."> <div id="autocomplete-results"></div>
  3. CSS Styling (Optional): Style the autocomplete results container according to your design preferences.

    css
    #autocomplete-results { border: 1px solid #ccc; max-height: 150px; overflow-y: auto; } .autocomplete-item { padding: 8px; cursor: pointer; } .autocomplete-item:hover { background-color: #f0f0f0; }
  4. JavaScript Logic: Write the JavaScript logic for autocomplete functionality.

    javascript
    $(document).ready(function () { // Sample data for autocomplete suggestions var autocompleteData = ["Apple", "Banana", "Cherry", "Date", "Grape", "Lemon", "Orange", "Peach", "Pear"]; // Input field and results container var inputField = $("#autocomplete-input"); var resultsContainer = $("#autocomplete-results"); // Event handler for input changes inputField.on("input", function () { var userInput = inputField.val().toLowerCase(); var matchedItems = autocompleteData.filter(function (item) { return item.toLowerCase().includes(userInput); }); // Display matched items in the results container displayResults(matchedItems); }); // Event handler for item selection resultsContainer.on("click", ".autocomplete-item", function () { var selectedValue = $(this).text(); inputField.val(selectedValue); resultsContainer.empty(); }); // Function to display results in the container function displayResults(items) { var resultsHTML = ""; for (var i = 0; i < items.length; i++) { resultsHTML += '<div class="autocomplete-item">' + items[i] + '</div>'; } resultsContainer.html(resultsHTML); } });
  5. Testing: Test your autocomplete functionality by typing into the input field, and you should see matching suggestions appear below the input.

Adjust the code as needed based on your specific requirements and styling preferences. The provided example is a basic implementation using jQuery, and you can enhance it further based on your application's needs.