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


15 Comments »

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

  6. Alan Holder
    6

    @Alex,

    I can see how that would be a recommendation. I do think that in practice, posts are much easier, as you do not have to mess so much with url encoding/decoding so much. It’s also slightly more obscure to mess with from a security perspective.

    By the way, personally I like the “TagDragon” autosuggest script very much:

    http://www.s3maphor3.org/tagdragon/

    – Alan

  7. ilya
    7

    To ignore keyup event from keys like shift, caps and other you may want to make ‘var search’ a global variable and compare it with a value of txt_search before doing ajax request. This would save a few unnecessary post calls.

    var search = “” ;

    $(“#txt_search”).keyup(function()
    {
    if (search != $(“#txt_search”).val())
    {
    // Trigger AJAX request
    search = $(“#txt_search”).val();
    }

    });

  8. Samuel ROZE
    8

    As we can see at http://unixpapa.com/js/key.html, the keyup event isn’t supported by all browsers, so why not using the “change” event, which may be better supported?

  9. Pingback:
    9
    One Row VS. Other Tables

    [...] make an autosuggest feature. Plugins | jQuery Plugins And here's a tutorial I found right quick. Jetlogs.org jQuery: Auto-suggest with keyup() event Reply With Quote   + Reply to Thread « Previous Thread [...]

  10. Pingback:
    10
    need coding help - Hot Scripts Forums

    [...] post some php code that would pull the Apt names from a database using php. Some good examples: Jetlogs.org jQuery: Auto-suggest with keyup() event jQuery Auto Suggest with MySQL | jonathan stegall: creative tension Also a nice easy to use [...]

  11. amritags
    11

    Can u tell what are changes to be made if am using a mysql db instead of an array to retieve words?????

  12. AIM web design company
    12

    Web Design Company is professional website design company in Hong Kong, web design service provider in hong kong.

  13. Tierno silver
    13

    本店專門經營國際標淮925純銀首飾,包括頸鍊、手鍊、耳環、戒指、手鐲及腳鏈,純銀,產品主要來源包括台灣、泰國、意大利及香港。產品款式以時尚簡約為主,有些首飾會鍍上白金,黃金或玫瑰金,令首飾看上更有光澤及高貴。配石方面本店採用方晶鋯石,閃亮度能和天然鑽石媲美。

  14. 皇室包裝搬運公司
    14

    皇室包裝搬運公司一向致力提供各種搬運服務,專業服務包括: 搬遷住宅、寫字樓、廠房等; 搬運各類大小貨品; 提供長短期存倉服務。另特設嶄新家居滅蟲服務(由維康滅蟲服務有限公司提供),好讓各住客用戶日後免受昆蟲滋擾。

  15. mohsin butt
    15

    Best Classified Software now in Just 99$, 1Classified Script gives an option to BUYER and SELLER to communicate directly.
    http://www.1classifiedscript.com

RSS Comment Feed Comments RSS |trackback TrackBack URI

Leave a comment

  • Archives

  • Donations

  • Social Bookmarks

  • Jetlogs.org
    Some Rights Reserved 2007
    Creative Commons License