Would you like to be notified for every new articles? Please click HERE to subscribe for newsletter.

JQuery Cool Auto-Suggest

  • Posted on: 11 June 2011
  • By: admin

This is the second release of my jQuery Cool Auto-Suggest plugin. This new version still has the same features from the older one. The features are :

  • Support ID field.
  • Support image thumbnail and description
  • Support form submission on click.
  • Callback function when item selected.
  • Error callback function for custom error message.
  • Able to pass additional request parameters based on other input's value.

You might have been searching a jQuery plugin which can get one record from database and display the fields on some input elements. My jQuery FetchRow plugin might be the solution.

Current Version

The current version is 2.3 which has some new features such as error callback function for custom error message and also the capability to pass additional request parameters based on other input's value. The full source code and example can be downloaded from https://github.com/w3shaman/jquery-coolautosuggest/releases/tag/2.3.

How To Use

The basic way of using this plugin did not changed from the previous version. First, include jQuery and this plugins inside the <head> tag.

<script language="javascript" type="text/javascript" src="js/jquery.js"></script>
<script language="javascript" type="text/javascript" src="js/jquery.coolautosuggest.js"></script>

Also include this CSS file for styling the suggestions.

<link rel="stylesheet" type="text/css" href="css/jquery.coolautosuggest.css" />

Prepare the textbox.

<input type="text" id="text1" name="text1" />

And finally, initialize the cool auto-suggest textfield. There are some options in this example.

<script language="javascript" type="text/javascript">
$("#text1").coolautosuggest({
  url:"data.php?chars=",
  showThumbnail:true,
  showDescription:true,
  submitOnSelect:true
});
</script>

If the showThumbnail option set to true, it will display image thumbnail on every suggestion item. If the showDescription option set to true, it will show description text on every suggestion item. If the submitOnSelect option set to true, the form (if you have one) will be submitted once you click one of the suggestion items. More complete options and examples can be seen at the Demo page.

Using The Callback

Callback function is the new feature in this version. This is how we use it.

<script language="javascript" type="text/javascript">
$("#text1").coolautosuggest({
  url:"data.php?chars=",
  showThumbnail:true,
  showDescription:true,
  onSelected:function(result){
    // Check if the result is not null
    if(result!=null){
      $("#text1_id").val(result.id); // Get the ID field
      $("#text1_description").val(result.description); // Get the description
    }
    else{
      $("#text1_id").val(""); // Empty the ID field
      $("#text1_description").val(""); // Empty the description
    }
  }
});
</script>

When you made a selection on one item, the selected object will be passed as a parameter to the callback function. In this case, as the result variable. And then, the callback function will be executed. The content of that function is up to you. You can write your own function to handle that selected object.

Server Side Script

This is the server side script that we used. The transferred data is encoded in JSON format. This is the example.


<?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="test";
$password="123456";
$database="test";

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

$arr=array();
$result=mysqli_query($con,"SELECT * FROM people WHERE name LIKE '%".mysqli_real_escape_string($con,$_GET['chars'])."%' 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);
?>
CSS

You can change the suggestions' styles by customizing the CSS file. Here is the content for the CSS file

/* Style For Suggestions */
 
/*
 For creating side border like this
 | item 1   |
 | item 2   |
 */
.suggestions .suggest_item{
	padding-bottom: 2px;
	padding-top: 2px;
	background-color:#EEEEEE;
	border-left:1px solid #CCCCCC;
	border-right:1px solid #CCCCCC;
}
 
/*
 For creating top border like this
 ------------
   item 1
   ...
 */
.suggestions .suggest_item.first{
	border-top:1px solid #CCCCCC;
}
 
/*
 For creating bottom border like this
   ...
   item 2
  ------------
 */
.suggestions .suggest_item.last{
	border-bottom:1px solid #CCCCCC;
}
 
/*
 For coloring the selected item
 */
.suggestions .suggest_item.selected, .suggestions .suggest_item.selected .description{
	background-color:#999999;
	color:#FFFFFF;
	cursor:pointer;
}
 
/*
 Image thumbnail
 */
.suggestions .suggest_item .thumbnail{
	background-color: transparent;
	background-position: top center;
	background-repeat: no-repeat;
	margin: 1px 2px 1px 2px;
	float: left;
	width: 50px;
	height: 50px;
}
 
/*
 Description
 */
.suggestions .suggest_item .description{
	font-style: italic;
	font-size: 11px;
	color: #777;
}
Demo

You can see the live demo and how to use this plugin here.

Download

The full source code is available on GitHub: https://github.com/w3shaman/jquery-coolautosuggest. Please feel free to contact me if you want to make any contribution for this small project.

Installation Using npm or bower

You can download then extract the script manually or install it using npm or bower command.

Using npm:

npm i jquery-coolautosuggest

Using bower:

bower install jquery-coolautosuggest

 

Comments

I downloaded this plugin and it already had this encodeURI modification, but it's wrong. It needs to use encodeURIComponent(). We are encoding a URI component after all. For example, encodeURI() does not encode things that need to be encoded for a URI component. Using CodeIgniter, that is unacceptable.

Hello,
I have replaced php call with java servlet call and trying to form json object, something like this
[{"id" : 1, "data" : "London"} , {"id" : 2, "data" : "Munich"}]
but getting no output.
Can you please suggest what is correct synatx required for JSON

@Victor: I think your JSON format is already correct. Maybe there is another cause. Did you get error message?

You can solve the problem with the empty POST variable by changing the following code in jquery.coolautosuggest.js

Change:

if(me.idField!=null){
if(me.checkSelected(me.textField.val())==false){
me.textField.val("");
me.idField.val("");
}

To:

if(me.idField!=null){
if(me.checkSelected(me.textField.val())==false){
me.idField.val("");
}

Firstly, many thanks for creating and sharing this plugin. I've tried several jQuery autosuggest plugins, but this one is the fastest and smallest in size. Perfect.

I don't know whether you continue to work on it, but I would really like to see the feature where the function is fired again after you select 1 result separated by comma.
Eg. I start typing something, get a list of results, select 1 result which is copied into input field, then add a comma and start typing again - and the plugin gives suggestions again.

Do you mean it's like a tagging? Well, I have a script like that but it's still incomplete. I will see if I can add that functionality to this plugin.

yes, yes, yesssss! That's real cool! I've spent few hours to implement a autosuggestion plug-in and finally i've found it.
Manu thanks to do this fine work! You save my live! :-)
Good job!

Great information... Thanks so much for writing all of the excellent information!

ar condicionado automotivo

I am trying to do an onchange event to run a other ajax request but I am not sure if that work or if this even allowed...

$("#CustomerLocationName").coolautosuggest({
url:"includes/findcustomerlocation.php?chars=",
showThumbnail:false,
showDescription:true,
onSelected:function(result)
{
if(result!=null){
$("#CustomerLocationId").val(result.id); // Get the ID field
$("#CustomerId").val(result.customerid); // Get the description
}
else{
$("#CustomerLocationId").val(""); // Empty the ID field
$("#CustomerId").val(""); // Empty the description
}
}
});

can i inject a javascript function like : " onchange(getcustomeruser(CustomerId.value) " ??

ps love the functionality just not that familiar with jquery.... keep up the good work!!

How to implement multiple values using this? Just like http://jqueryui.com/autocomplete/#multiple-remote

Thanks!

Hi There, i've found and try to implemented this autosuggest in my dev site, but i've a little problem, i can't get the right data while URL for retreiveiw data is based on other selectbox / optionbox, while i change the value on checkbox the result always as save as the first value of selected selectbox value.

$("#JK").change(function(){
$("#Istri").coolautosuggest({
url:"ajax.php?qm=suggest&Unit=" + $("#Unit").val() + "&JK=" + $("#JK").val() + "&Nama=",
showThumbnail:false,showDescription:true,idField:$("#IDIstri"),
width:180,minChars:2,submitOnSelect:false
});
});

when i change the value of selectbox Unit or JK, the URL request will still same as the first value :(

Please suggest me on how to fix this !

Its works great in my first installation. You have answered everything in your blog like steps to install, customization and even PHP Code. So almost it answered everything for a general user especially to me.

Thank you for your plugin & work.

Hi
Possible to limit size of dropdown to certain length, i.e, scrollable dropdown?
Also, can the dropdown be triggered onFocus. after writing "a", and clicking someplace else, when the input is focused back, the dropdown should show with the matching terms.

Thanks.

TThe information of the article proved very much helpful for me as this is very easy to use. his PHP download script has many features like the increased configurable speed and stress balls resumable download capability is also very high in this.

Hi,
i want send the id-field to the search.php, but i have no idea how to get the id variable name.
i don't know how to get the variables id, discription, profession and picture.
Please can you help me?

I want to send the varibles like this:

Thanks and sorry for my bad english :-)

Pages

Add new comment

Limited HTML

  • Allowed HTML tags: <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.