Due to a request from a friend, here is a tutorial on how to do an auto-suggest script using jQuery and the keyup() event. The program logic of this script is based on the AJAX suggest script from w3schools but with some improvements on the efficiency, ease of use and customization by using jQuery.
The basic logic of an auto-suggest script is that for every keystroke that a user enters on a textfield, the script must send an AJAX request and validate which words in a dictionary most closely resembles the current input.
First of all, we will need to have a textbox field for our search field. Then let’s give it an id called txt_search (#txt_search)
<input type="text" id="txt_search" name="search">
Next, we will need a <span> or a <div> where our auto-suggest results will show up. Let’s give this an id called suggest (#suggest)
<span id="suggest"></span>
Now, this is where the keyup() event comes in. For every keystroke that the user makes on the search input box, we must trigger an AJAX request. However, if we do not have any text on the search input box, no AJAX request should be triggered at all. Here is how it should look like:
$("#txt_search").keyup(function()
{
var search;
search = $("#txt_search").val();
if (search.length > 0)
{
// Trigger AJAX request
}
else
{
// Empty suggestion list
$("#suggest").empty();
}
});
And finally, to trigger the AJAX request itself, we must call on jQuery’s $.ajax() function to send the request. In this case, we must make an AJAX request to the backend which will check for the matching suggestions. For this tutorial, we will name our backend dictionary.php And upon success, we must clear the current contents of the #suggest container and replace it with the AJAX response:
$.ajax(
{
type: "POST",
url: "dictionary.php",
data: "search=" + search,
success: function(message)
{
$("#suggest").empty();
if (message.length > 0)
{
message = "Do you mean: " + message;
$("#suggest").append(message);
}
}
});
Now the backend’s job is to search the dictionary for the matching search term. For this tutorial, the dictionary will be in the form of an array. However, the dictionary source can be substituted by a flat file or database results (caution in using DB resources, especially in high-traffic conditions. Use a DB result cache if possible). The output would be a comma-separated list of words that match the search term. Here is how the PHP script would look like:
<?php
$search = strtolower($_POST['search']);
$search_length = strlen($search);
$suggest = array();
$dictionary = array('C++', 'Smalltalk', ...);
foreach ($dictionary as $word)
{
if($search == substr(strtolower($word), 0, $search_length))
{
$suggest[] = $word;
}
}
echo implode(', ', $suggest);
?>
In the end, here is how the auto-suggest will look like:
jQuery Auto-suggest Tutorial Demo
You can download the full demo here:
Download the jQuery Auto-suggest Tutorial









