jQuery Cool Auto-Suggest

JQuery plugin for creating Ajax driven autocomplete/autosuggest with many options such as thumbnail image, before and after load callback function, default template overriding, etc. Look and feel can be freely customized using CSS.

Classic Style

The classic style of auto-suggest. It takes just one parameter, the URL to retrieve the data.

Public figure name :

The code :

$("#text1").coolautosuggest({
  url:"data.php?chars="
});
Using ID Field

The auto-suggest can also return an ID. You just need to prepare the input element for storing it and then pass one additional parameter, idField.

Public figure name :
ID :

The code :

$("#text2").coolautosuggest({
  url:"data.php?chars=",
  idField:$("#text2_id")
});
Image Thumbnail And Additional Description

The auto-suggest can also display image thumbnail and additional description. You have to pass two additional parameters, showThumbnail, and showDescription and then set their value to true.

Public figure name :

The code :

$("#text3").coolautosuggest({
  url:"data.php?chars=",
  showThumbnail:true,
  showDescription:true
});

Note :

Image thumbnail's width and height can be set from the CSS file.
For the best output, I recommend that all images must have the same width and height.

Some Other Options

There are also some usefull options such as:

  • width. Basically, the auto-suggest width will be the same as the textfield's width. By using this parameter, you can customize the auto-suggest width to suit your need.
  • minChars. By default, the auto-suggest will appear if you type the first letter. You can set the number characters typed to trigger the auto-suggest to appear by using this parameter.
  • submitOnSelect. By setting this parameter value to true, the form will be submitted once you click one of the item in the auto-suggest list.
Public figure name :
ID :

The code :

$("#text4").coolautosuggest({
  url:"data.php?chars=",
  showThumbnail:true,
  showDescription:true,
  idField:$("#text4_id"),
  width:300,
  minChars:2,
  submitOnSelect:true
});
Callback Function

There is a callback function which can be used via onSelected parameter. This callback function will be executed when you made a selection on one item (by clicking it or pressing 'Enter'). By using this callback feature you can retrieve the selected object to be used later in your code.

Public figure name :
ID :
Profession :
Picture :

Sample code :

$("#text5").coolautosuggest({
  url:"data.php?chars=",
  showThumbnail:true,
  showDescription:true,
  onSelected:function(result){
    // Check if the result is not null
    if(result!=null){
      $("#text5_id").val(result.id); // Get the ID field
      $("#text5_profession").val(result.description); // Get the description
      $("#picture").html('<img src="' + result.thumbnail + '" alt="" />'); // Get the picture thumbnail
    }
    else{
      $("#text5_id").val(""); // Empty the ID field
      $("#text5_profession").val(""); // Empty the description
      $("#picture").html(''); // Empty the picture thumbnail
    }
  }
});

Note :

This callback feature can also be used as the alternative to get the ID of the selected item and also submit the form after you made the selection.

Additional Dynamic Query String

We can pass additional dynamic query string to the request URL. For the example, we may need to filter the autocomplete list based on the previously selected profession.

Profession :
Public figure name :
ID :
Picture :

Sample code :

$("#text6").coolautosuggest({
  url:"data.php?chars=",
  showThumbnail:true,
  showDescription:true,
  additionalFields:{
    "&profession=" : $("select[name=profession]") // We can use more than one criteria if needed.
  },
  onSelected:function(result){
    // Check if the result is not null
    if(result!=null){
      $("#text6_id").val(result.id); // Get the ID field
      $("#picture").html('<img src="' + result.thumbnail + '" alt="" />'); // Get the picture thumbnail
    }
    else{
      $("#text6_id").val(""); // Empty the ID field
      $("#picture").html(''); // Empty the picture thumbnail
    }
  }
});

Note :

The additionalFields should be in key-value pair. The string we used for the key is flexible, it can be "&profession=" or "/profession/" or anything depend on your needs.

The value part should be the element object, not its value. As we see in the example, the correct value is $("select[name=profession]") not $("select[name=profession]").val().

Error Callback

We can also use custom error callback function to display custom error message when there is something wrong on the autocomplete process.

Public figure name :

Sample code :

$("#text7").coolautosuggest({
  url:"notfound.php?chars=", // We point to wrong URL to raise error.
  onError:function() {
    alert("Hey, it seems something error has happened.");
  }
});
Before And After Request Callback

By using this callback, we can display loading indicator image when the autocomplete list is being populated then hide it when the list is completely populated. Of course there are other possibilities we can do using these callback functions.

  • onRequest. This parameter can be used to call a function before the AJAX request is sent.
  • onComplete. This parameter can be used to call a function after the AJAX request is completed.
Public figure name :
* The loading indicator will appear when we are typing some letters.

Sample code :

$("#text8").coolautosuggest({
  url:"data.php?chars=",
  onRequest:function() {
    $("#loading8").show();
  },
  onComplete:function() {
    $("#loading8").hide();
  }
});
Default Template Overriding

We can also override the default HTML template for the autocomplete list item. The following example demonstrates the template overriding trick to display the item description and thumbnail on mouseover only.

Public figure name :

Sample Code

$('#text9').coolautosuggest({
  url:'data.php?chars=',
  showThumbnail:true,
  showDescription:true,
  template: '<div id="[rowId]" class="[rowClass]" id_field="[id_field]" seq_id="[seq_id]"' +
        ' onmouseover="$(&quot;#[rowId] .hide&quot;).show()"' +
        ' onmouseout="$(&quot;#[rowId] .hide&quot;).hide()">' +
      '<div class="[thumbnailClass] hide" style="[style];float:right;display:none;"></div>' +
      '<div class="[textClass]">[text]</div>' +
      '<div class="[descriptionClass] hide" style="display:none;">[description]</div>' +
    '</div>'
});

The example above is just one thing you can do with this option. There are many other possibilities you can achieve by using this feature.


Note :

In the sample code, you can see that there are some placeholders such as [rowId], [rowClass], etc. Just leave them unchanged because they are required in order to make the auto-suggest works properly.


Server Side Code

The server side code below is writen in PHP. Of course you can use other languages such as Python, Node JS, etc. as long as they can output the JSON format.

<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Content-type: application/json");

$host="localhost";
$username="root";
$password="";
$database="test";

$con=mysqli_connect($host,$username,$password,$database);

$arr=array();

$profession = "";
if (isset($_GET['profession'])) {
    $profession = " AND description = '" . mysqli_real_escape_string($con, $_GET['profession']) . "' ";
}

$result=mysqli_query($con,"SELECT * FROM people WHERE name LIKE '%".mysqli_real_escape_string($con,$_GET['chars'])."%' " . $profession . " ORDER BY name LIMIT 0, 10");
if(mysqli_num_rows($result)>0){
    while($data=mysqli_fetch_row($result)){
        // Store data in array
        // You can add any additional fields to be used by the autosuggest callback function
        $arr[]=array(
            "id" => $data[0],
            "data" => $data[1],
            "thumbnail" => 'thumbnails/'.$data[3],
            "description" => $data[2],
            // Additional fields (if any)...
        );
    }
}

mysqli_close($con);

// Encode it with JSON format
echo json_encode($arr);

For PHP language, you can also use the PDO instead of mysqli_ like following.

<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Content-type: application/json");

$host="localhost";
$username="root";
$password="";
$database="test";

$db = new PDO("mysql:host=$host;dbname=$database" , $username , $password);

$arr = array();

$where = array();
$where[':name'] = '%' . $_GET['chars'] . '%';

$profession = "";
if (isset($_GET['profession'])) {
  $profession = " AND description = :description ";
  $where[':description'] = $_GET['profession'];
}

$sql = "SELECT * FROM people WHERE name LIKE :name " . $profession . " ORDER BY name LIMIT 0, 10";

$query = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$query->execute($where);

$result = $query->fetchAll();
if ($query->rowCount() > 0) {
  foreach ($result as $data) {
    // Store data in array
    // You can add any additional fields to be used by the autosuggest callback function
    $arr[]=array(
      "id" => $data['id'],
      "data" => $data['name'],
      "thumbnail" => 'thumbnails/'.$data['photo'],
      "description" => $data['description'],
      // Additional fields (if any)...
    );
  }
}

// Close connection.
$db = null;

// Encode it with JSON format
echo json_encode($arr);