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.

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 current version is 2.3.3 which has some new features such as callback function for custom error message, additional query string based on the other input value, and also mobile device support. The full source code and example can be downloaded from https://github.com/w3shaman/jquery-coolautosuggest/releases/tag/2.3.3.

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

Looks great. Very well done. Can't wait to test it out.

(one problem though, it looks like the download link is not working)

Anyways, keep up the great work. It's obvious you've got mad skills.

Thanks for notifying me about the problem. It seems I accidentally delete that file in my server :). I just upload it back and the download link is working now. Please test it.

link to download, not work.

good job man

The list of results is very long. How do I divide it into multiple pages?
Thanks,
Bye,
Michele

Hi Michele. I think the best way you can do is limiting your query result. If you think the number of rows is too long, you can reduce it using LIMIT statement in you query.

How to execute a function after selecting a child

regards
ajay

I'm sorry. Currently, this plugin has no support for that. I consider to put that feature for the next version.

Hi, using this to with a VB script so have had to format the json return string manually but when entering text into the text box, I get "Sorry, an error has occurred!" - which isn't very helpful! I've checked in PHP and the format of my string is the same as outputted via json_encode. I've looked in firebug and the string is being returned properly to the script. Any ideas?

I had the "Sorry, an error has occurred!" as well and discovered that it occured when data had special characters in it like â or ü. For instance jo crashed when jonaslân was in the list of answers.

"data" => utf8_encode($data[2]),
solved my problem.

Hope it helps someone else.

Thanks, saved a lot of time debbuging. Thanks

If I use two inputbox or more in a table at the same time, and one inputbox is under another one, when I enter the word in the lower inputbox, the suggestionbox has the problem -- it seems the suggestion words appears twice, and the size suggestionbox is stretch very long.

Any ideas to solve the problem?
Thanks.

Sharp

good

I will tryout this plugin in my current project. My client wants Auto-suggest to help visitors find content on their site that's relevant. I hope this plugin will achieve the FE requirements.

How to change the js code to support Chinese?

I really like the look of this plugin and it appears to be very flexible - thanks for all your good work!

Would it be very difficult to use this on more than one field in a form? What would I need to do so the lookup could be done on two different tables in a db within the same form? Also - I guess I would need to 'tell' the css where to put the list depending on which field was being edited, correct?

Any help would be much appreciated - thanks!

I really like the look of this plugin and it appears to be very flexible - thanks for all your good work!

Would it be very difficult to use this on more than one field in a form? What would I need to do so the lookup could be done on two different tables in a db within the same form? Also - I guess I would need to 'tell' the css where to put the list depending on which field was being edited, correct?

Any help would be much appreciated - thanks!

I'm sorry about those two previous comments / questions, I figured out how to handle the multiple fields in a form and how to search different tables in a database by looking at your demo. Should have done that FIRST.

I would like to use this plugin with a form that adds & edits records from MySQL db. Is there a way that I can stuff a value in to the text field on page load if the user is 'editing' an existing record and something was previously in that field?

Overall this plugin lives up to its' name - Cool, but it throws an error for no apparent reason with certain data strings being returned (like "To"). This can present a real problem when filling out a cool field to try to bring up a record for editing and you can't get past the first two letters!

Great work, works perfect!

Is it possible if I use the form reverse order?
If I type in ID field id of “Public figure name” then it automatically fills out other fields and no need to ID field gives auto suggestion

Great work, works perfect!

Is it possible if I use the form reverse order?
If I type in ID field id of “Public figure name” then it automatically fills out other fields and no need ID field give auto suggestion

I think this plugin can't do that. Even if it can, it can't wear 'autosuggest' name anymore. But your question gives me idea to create another plugin which can do that kind of thing. :)

Sooo... We are waiting for that plugin which can do that :)

I copied the code, and only modified the data.php to pull data from my existing db. I tested the data.php?char=b code, and I do get a valid data streaming via the json code.

So after implementing the above, i thought the original code on the original index.php would work, but nothing happens :(

I'm new to this, and was wondering, how does the js know there are keystrokes when the user is typing in the text field?

Any help would be appreciated!

TW

Yes, the javascript know the keystrokes event in textfield. In jQuery, you can bind an event listener using the keyup, keypress, or bind function.
Maybe this link can help:
http://api.jquery.com/category/events/

hi, i cant download the file... i have an interrupted download :(

best regards !

Hi!

Like this plugin a lot but there are some places you should check if me.idField is null.

Two places in the checkKey function:


Instead of:


me.idField.val(target.attr("id_field"));


Check for null (as I can see that you do in other functions):


if(me.idField != null) {
me.idField.val(target.attr("id_field"));
}

Regards - Andreas

Yes, you're right. Thanks for notifying me about that. The fix will come in the next version. I'm still working on it.

Thanks for the plugin :) works really well. I really need to distinct the results, e.g: if I type 'wo' 8 results come up with 'work' and 2 results come up with 'work hard'. I just want the plugin to show 1 time 'work' and 1 time 'work hard'. How can I do this?

Thanks in advance!

Hmm.. maybe you can use SELECT DISTINCT in your server side script.

Very usefull plugin! Thanks alot.
But its a pitty, that I cant use it, becaus I cannot limit my results for the users of my site. That would not be usefull for them.
So, is there a possibility for using a scrollbar?
That would be very very great!

Very usefull plugin! Thanks alot.
But its a pitty, that I cant use it, becaus I cannot limit my results for the users of my site. That would not be usefull for them.
So, is there a possibility for using a scrollbar?
That would be very very great!

I'm not sure, but there is a "div" with class "suggestions" that holds all the populated suggestions. Maybe you can use CSS to limit its "max-height" to some height and then use the "overflow:auto".

This script doesn't work on IE7??

I'm not sure, I only try it in IE 8 and works fine.

put an online example , retard.

I did.. It's in here :
http://stuff.w3shaman.com/jquery-plugins/coolautosuggest/

Have to be a jack-ass about it. And there was a link already. He did't have to make or share this plugin... so F-off...

I have installed your files on my server... I am testing it it with french characters and I am having issues.

I am doing tests with a record named "Les confessions de Stéphane Rousseau".

- If I type "rousseau", it works fine.
- If I type "stephane rousseau", it works fine.
- If I type "stéphane rousseau" (with the accents), it can't find it.

I have used a log file to see that when the data.php script is called, the string is now stéphane

What do you suggest to handle this situation ?

I have noticed that the form submit is triggered only when the selected item in the list is "clicked" using the mouse pointer. I was wondering if it would be possible to trigger also when the user presses on the ENTER key.

I try your script with no modified source, but I got this errot 'Sorry, an error has occured!' when typing on
the input box, any idea whats wrong?

use firebug tab console to get information about what is wrong

good luck

Hi

First of all I'd like say that it's a great plugin.

But I came across 2 nasty issues:

1)
The plugin seems to empty the textfield it is connected to.
On load I fill the value of the text field with a value from a database using php. This is overriden by the plugin the field is empty.

2)
If user doesn't select anything but types a new item to be added to the list and submits the textfield doesn't send that value to the Php $_POST array. That namespace is empty:
Array
(
[textfield] =>
)

(of coarse PHP should handle the new item adding but that's something I solved)

Is there a possibility to change any of the parameters / source code to alter these two aspects?

thanx a lot any way

grtz I.

If the user types in a new item (in case the option is not available in the list) the text field does not send that value to $_Post ...

Could you please let know what is the solution for this?

If user doesn't select anything but types a new item to be added to the list and submits the textfield doesn't send that value to the Php $_POST array.

Could you please provide a solution to this problem?

I also get the "Sorry, an error occured" error, when I type and there are at least 1 result to show :|

I saw that a 404 error on the source url causes this.

I found, that scrip support only english characters.
Encoding characters in ajax call ( and decoding on server) makes it work.
At line 45:
url:me.callBackUrl + $(this).val(),
change to:
url: me.callBackUrl + encodeURI($(this).val()),

@Alex Borisov: When I write this plugin, I haven't tested it with non-english character. Thank you for your suggestion, I will update this script soon.

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.