jQuery: Auto-suggest with keyup() event

Posted by Jetlogs @ 4:59 pm
Category: jQuery

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


5 Comments »

5 Comments to “jQuery: Auto-suggest with keyup() event”

  1. RaMa-NoOb
    1

    hehe hope we can develop our own phprunner like script :)

  2. Alex
    2

    Small nit… The W3 consortium recommends POST only for requests that do change something on the server, and use GET for fetching information based on parameters.

    Using GET would therefore be the better solution for the case above (and, browsers could cache the results, so that subsequent requests for the same keyword would not need to go to the server).

  3. name
    3

    Good day!,

  4. name
    4

    Hi!,

  5. Cyril Gupta
    5

    Great post… I am going to adapt it, and use it for an ASP.Net Autosuggest box that I will build using a PageMethod.

    Cheers!

RSS Comment Feed Comments RSS |trackback TrackBack URI

Leave a comment

  • Archives

  • Donations

  • Social Bookmarks

  • Jetlogs.org
    Some Rights Reserved 2007
    Creative Commons License