In the last few days I’ve started using the jQuery JavaScript library. To experiment with this great piece of software I’ve decided to implement an AJAX auto-complete feature. jQuery makes remote scripting a piece of cake and that led me to spend more time coding additional functionalities for the auto-complete field. In this post I’ll explain how to use my auto-complete field and in a following post I’ll explain all the code. So let’s start!
Before continuing let’s see how the auto-complete field looks like. Start typing some color name in the input field bellow to see how it works:
Pretty hugh? Besides the auto-complete code we need the jQuery library along with its Dimensions plug-in (all files are linked at the end of this post). Let’s include the files into our page:
<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dimensions.js"></script> <script type="text/javascript" src="autocomplete.js"></script>
Now we need to call the function that will bring life to our auto-complete field - setAutoComplete.
<script type="text/javascript"> $(function(){ setAutoComplete("searchField", "results", "autocomplete.php?part="); }); </script>
The call to setAutoComplete is inside a jQuery special code that is only executed when the DOM is ready, or in other words, when all the code is already loaded. The setAutoComplete function takes 3 parameters:
Be aware that the URL should reflect your remote script and that it will be combined with the text typed in the input field.
Now we include our stylesheet to define the look of the elements. We need to define the styles of the div that will contain the results, they include two classes for the selected and unselected items. Take a look at the CSS file linked at the end of this post. There is also a style for the input field.
<link rel="stylesheet" href="autocomplete.css" type="text/css">To finish the client side part now we need to define the code of the input field as follows:
<label for="searchField">Colors: </label> <input type="text" id="searchField" name="searchField">
We are almost there! Now that the client side is finished it’s time for the server script. Here is an example of a script that try to match colors. I’m using PHP but you can use whatever language you prefer for the job, of course. You just need to return the results as an array encoded as JSON.
// define the colors array $colors = array('black', 'blue', 'brown', 'green', 'grey', 'gold', 'navy', 'orange', 'pink', 'silver', 'violet', 'yellow', 'red'); // check the parameter if(isset($_GET['part']) and $_GET['part'] != '') { // initialize the results array $results = array(); // search colors foreach($colors as $color) { // if it starts with 'part' add to results if( strpos($color, $_GET['part']) === 0 ){ $results[] = $color; } } // return the array as json echo json_encode($results); // or return using Zend_Json class // require_once('Zend/Json/Encoder.php'); // echo Zend_Json_Encoder::encode($results); }
Done! As said before, we return the data as an array encoded as JSON. If you are running PHP >= 5.2.0 or the json extension you simply use json_encode for the job. Another option is to use Zend_Json_Encoder from the Zend Framework!
You should have a working auto-complete field by now! Note that we don’t need to explicit create the result div because it’ll be created automatically. You should also note that the current script can be improved a lot and is limited to just one auto-complete field per page!
Keep tuned, in the next post I’ll explain how the JavaScript works!
Thank you!
Update: Click here to read the post where I explain the JavaScript code!
Files needed:
Auto-Complete (All files)
jQuery JavaScript Library
jQuery Dimensions Plug-in
Zend Framework
57 Responses
Frank
May 26th, 2007 at 6:38 am
1For php4 users (if you’re still bound to) you can use http://mike.teczno.com/JSON/ to encode to JSON.
// return the array as json with PHP 4 and Services_JSON
require ‘JSON.php’;
$json = new Services_JSON();
echo $json->encode($results);
Frank
May 26th, 2007 at 8:27 am
2What’s a little pitty is, that mozilla tends to remember what has been already entered in that field. This is great in general but with your own autocomplete it is not because this is displayed above the autocomplete list. This can be made with the autocomplete attribute setting to off. Maybe it makes sense to put this into the .js as well?
This is the code that did the job for me (tested in firefox 2.x) in autocomplete.js inserted at line #40 in function setAutoComplete:
// remove browsers autocomplete
acSearchField.attr(”autocomplete”,”off”);
more info: http://chrisholland.blogspot.com/2004/11/banks-protect-privacy-disable.html
Frank
May 26th, 2007 at 9:10 am
3Another comment: Using the PHP4 JSON.php lib is a bit problematic when it comes to unicode. For some german umlauts the code has got bugs resulting in problems for the autocomplete to properly work. It is strongly suggested in such cases to migrate to php5 as with everything unicode related.
Frank
May 26th, 2007 at 9:38 am
4Well I don’t know what changed exactly (this is a joke, what changed is PHP to version 5.2.2), but calling the html (not any php) file gives a long list of javascript warnings already in jquery. my favorite ones are:
clearAutoComplete is not defined
or
Warnung: variable a hides argument
or
Warnung: variable i hides argument
I dunno what is going wrong here I’ll restart my system now.
Frank
May 26th, 2007 at 10:10 am
5Finally I rebuild all and even just opening the unzipped files directly from disc in firefox throws JS warnings. Can anyone confirm this?
fromvega
May 26th, 2007 at 11:13 am
6Hey Frank, disabling the browser auto complete is a good tip. Thank you! I’ll address this issue in the next version. I’m planning to transform it in a jQuery plugin as soon I have a little more time.
Maybe your problem is that you are returning invalid data! Since the script uses jQuery $.getJSON function you should only return JSON.
Frank
May 27th, 2007 at 11:48 am
7Hi fromvega! Yup that was my mistake, there was no proper JSON returned. If you’re after turning this into a jQuery Plugin (good idea!) keep in mind that it should work on multiple inputs on the same page. I could not figure out how to do that with your autocompete.
fromvega
May 27th, 2007 at 1:48 pm
8I’m glad it worked for you. And yes, the plugin will work on multiple inputs. I coded the current script mainly to study jQuery and its Ajax functions. To have multiple inputs with the current script you need to duplicate the code and rename the global variables for each input, like I described here in the Auto-Complete Field with jQuery - Code Explained
Frank
May 28th, 2007 at 5:15 am
9Okay, well, I see. Maybe it’s better to support an already existing project? I found
http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
which is an jQuery Autocomplete Plugin and it works very nice even without duplicating the sourcecode (which is not an option in my opinion). It already has some more nice options you should defenetly take a look there anyway even if you wanna start a plugin on your own.
fromvega
May 28th, 2007 at 2:28 pm
10Learning is what lead me to write these codes. I’m pretty sure there are a lot of similar scripts around the Internet. The one you linked is an example of a very good one, but I’ll keep writing my own code as it’s a way to improve my skills and help others detailing how they work.
Plug-ins tend to embed code to give freedom to the user, allowing multiple configurations for different usages. My code tend to fulfill my own needs and most of the times they won’t have a lot of configuration. Sometimes it can be better if your needs are similar to mine, reducing the code and making it simpler.
Jozef
October 31st, 2007 at 2:07 pm
11Hello Frank,
-I’m obviously not a programmer- So I am kind of embarrassed to ask.
What/how do I have to change to use autocompleter like a link (html link to a folder)?
Red - click - go to link- domainname/red/
Blue - click - go to link- domainname/blue/
For data source I can use XML or put the data inside the page.
(how is the data source format should be)
I wouldn’t mine paying for your help.
Thanks
jfk
fromvega
November 5th, 2007 at 6:00 pm
12Hello Jozef,
The code responsible for populating the list is:
newData += '<div class="unselected">' + json[i] + '</div>';So you would need to add a link tag, like this for instance:
newData += '<div class="unselected"> <a href="address">' + json[i] + '</a></div>';That’s way it will be clickable. For the red, blue thing your PHP script will probably need to send more information to the JavaScript code so then you can decide watch address to link.
I hope you could understand.
Bye.
Thailand Real Estate
December 30th, 2007 at 10:32 am
13Sorry where can i find dimensions.js and autocomplete.js file ?
fromvega
December 30th, 2007 at 4:17 pm
14Hi Thailand Real Estate, the files are listed at the end of the post, just before the comments! To get all the needed files, use this link: http://fromvega.com/code/autocomplete/autocomplete.zip
kpli
December 31st, 2007 at 2:01 am
15Thanks for the lovely post, i’ve read it with interest and had bookmarked this blog for future reference..keep em coming bro, and i wish you A Happy New Year !!
kpli
January 18th, 2008 at 7:58 am
16Hi..just stopping by to say a Happy New Year…interesting post there, and i’ve bookmarked this blog too…keep up the good job
ramon
February 13th, 2008 at 6:05 pm
17i just made a simple autcomplete jus like the one in the example i took it for inspiration and made some adjustments http://webs2.x1fmradio.com
Panzer
April 26th, 2008 at 9:09 pm
18Looks interesting, i might start using this on new websites i develop.
wissem
April 30th, 2008 at 10:45 am
19Greet work, thx!
rehman
May 5th, 2008 at 8:54 am
20Hi,I’ve a problem with your code:
When I put your zipped folder’s autocmplete.html file run on any browser it is not working with an javascript error.
If I put their in the
“start”
$(function(){
setAutoComplete(”searchField”, “results”, “autocomplete.php?part=”);
});
“end”
instead of
setAutoComplete(”searchField”, “results”, “autocomplete.php?part=”);
setAutoComplete(”searchField”, “results”, “http://fromvega.com/code/autocomplete/autocomplete.php?part=”);
it works.
In Short Your zipped code is not working But Online code work Smoothly.
So plz make your code perfect .
computerzworld
May 21st, 2008 at 1:35 am
21I have two fields that are used for autocomplete. I have used your script which runs perfect for one field but how can I use it for two fields? I have tried to modify it but I wasn’t able to modify it. Please help me. Thank you.
felicia
June 8th, 2008 at 1:27 am
22Thanks!
Works great!!
WoL
June 26th, 2008 at 6:07 am
23Im having the same problem as computerzworld, i cant get it to work with multiple search fields
Can anyone help?
fromvega
June 26th, 2008 at 6:20 pm
24Hi computerzworld, hi WoL. Like I said in another comment from the other post (http://fromvega.com/wordpress/2007/05/08/auto-complete-field-with-jquery-code-explained/), this example was not designed to be used efficiently with more than one field. Although, if you still wanna use it you will need to duplicate the code and rename the global variables and functions for each field.
FMS GROUP
July 28th, 2008 at 6:26 pm
25Thanks… `;)
Myrtle Beach Real Estate
July 29th, 2008 at 5:18 pm
26JQuery is awesome…
Marcum
August 15th, 2008 at 7:55 am
27Hi. Great code
I would like to one step further and have the array built from an xml file that is maintained on the website. I can use php simpleXml to get the titles into an array but I am not sure what changes are required to your code so that they are displayed. If it is not possible I will have just manually type them in, but then it is remembering to do it. Any help would be appreciated.
resim
September 16th, 2008 at 8:25 pm
28thank you.
WarpKat
September 22nd, 2008 at 5:18 pm
29@Marcum: read in your XML and parse it as an array, then toss the array to the function - not all XML is created equal… =:D
@All: Hello - this is a great short-method fix for what I needed to do, however, I do have a small inconvenience with it:
The list returned is actually longer than the window it’s on. Is there a way to turn the results into a scroll-barred list or maybe make it so that the list overlays on top of the window itself so the complete list can show?
I hope I explained that right…
fromvega
September 29th, 2008 at 9:36 am
30WarpKat, you can set the “hight” of the list container to something that you want then use “overflow-y: scroll” so you can have scrollbars
Charly
October 3rd, 2008 at 10:23 am
31How do I populate de Array dynamically from MySql Query ? Need Help Please.
Aaron Reynolds
October 7th, 2008 at 11:17 am
32Your code works well and I haven’t had to tinker yet.
Due to my Ubuntu install limiting me to PHP v5.1.2 currently I’ve had to use a 3rd party JSON encoder.
Ended up adapting rewriting it for the purpose.
Available at: http://dev.enjoyonline.co.uk/auto/ar_json_encoder.php.txt
I’ll be coming back to keep up with your other work, thanks - Aaron.
ev arkadaşı
October 20th, 2008 at 1:24 pm
33thank you
fromvega
November 24th, 2008 at 8:56 pm
34Hey Charly, you can’t populate directly from a MySQL query. You need to run the query, get the results and then put them into a PHP array. After that you can use a json encoder to send the resulting data back to jquery.
dino
December 1st, 2008 at 7:31 am
35hi vega
i have a question, how do i configure it to have a comma on every input
example
name1, name2, name3
whats happening now is when i put a comma on name1 then i choose again another name for example name2, name1 will be replaced by name2
another question is:
why is that when i input a word with one instace in my array in doesnt show up on the list but when i input with another input with many instances of that word it will show on list
thanks in advance and great job on the code
J
December 12th, 2008 at 2:03 pm
36Is there a way to limit the results?
refins
December 17th, 2008 at 1:11 am
37i am a newbie,
I have a same problem with Rehman, the autocomplete doesn’t work in localhost
if the script is setAutoComplete(”searchField”, “results”, “autocomplete.php?part=”);
but it does work well
if i put the script like this :
setAutoComplete(”searchField”, “results”, “http://fromvega.com/code/autocomplete/autocomplete.php?part=”);
because i’m using php v.5.1.1 so i try to download zend framework from
http://framework.zend.com/
(since there is a require file : Zend/Json/encoder.php)
but the problem still happens
i suppose it is caused by the version of the zend framework.
Could someone help me,please?
oyun hileleri
December 20th, 2008 at 3:22 pm
38help pls How do I populate de Array dynamically ( from MySql Query.
gebelikte moralsizlik
December 22nd, 2008 at 6:32 am
39Hey Charly, you can’t populate directly from a MySQL query. You need to run the query, get the results and then put them into a PHP array. After that you can use a json encoder to send the resulting data back to jquery.
car alarm system
February 6th, 2009 at 1:48 am
40great work!!
toki
February 28th, 2009 at 9:09 pm
41help pls How do I populate de Array dynamically ( from MySql Query.
Mira
March 31st, 2009 at 1:03 am
42Hi. Great code
I would like to one step further and have the array built from an xml file that is maintained on the website. I can use php simpleXml to get the titles into an array but I am not sure what changes are required to your code so that they are displayed. If it is not possible I will have just manually type them in, but then it is remembering to do it. Any help would be appreciated.
Webdesign Meppel
April 10th, 2009 at 4:52 am
43Awesome! One of the better auto-suggest scripts I have seen over the web. Need to try this one out!
plc
May 1st, 2009 at 11:23 pm
44Script does not display results if fonts are resized (ctrl + in firefox). Needs to recalc the result div before updateing the div results.
Thi Ha
June 16th, 2009 at 3:36 am
45awesome. works like charm.
Although I don’t know the back-end work, this is the simplest example I have ever find.
Only one question
How to show the not find message when no matching.
Cheers.
Thanks.
Thi Ha
Thi Ha
June 16th, 2009 at 4:14 am
46I got it but just adding this
if(empty($results)){
$msg[0]= “No matching”;
echo json_encode($msg);
}else{
echo json_encode($results);
}
Another question is where to change the font size, it looks smaller.
thanks
thi ha
ZK@Web Marketing Blog
June 21st, 2009 at 12:52 am
47It is built on top of the DOM, and unfortunately, the DOM is not always fun to work with. Luckily, we have an excellent DOM slicer and dicer that we can use alongside Strophe, the jQuery library.
Komik Videolar
July 12th, 2009 at 8:07 am
48Thank all.
Leon
July 17th, 2009 at 3:26 pm
49Hi there, just a simple question… This autocompleter works if there are 2 text box in the page, because i’ve been trying make it and it doesn’t. Actually it seems that only take the last autocomplete that I wrote in my code… P.E:
$(function(){
setAutoComplete(”searchField”, “results”, “autocomplete.php?part=”);
setAutoComplete(”searchField2″, “results2″, “autocomplete2.php?part=”);
});
this doesn’t work and i don’t know why… if anybody could help me please…!!!
P.D.- Sorry about my english, I know it’s not very good looking… jejejeje…
maie
July 20th, 2009 at 7:56 am
50hello
In my script i made an array of text fields dinamically from the database
so i want to apply the auto complete on each one but when i make that it does not work please help ASAP you can send answers on my mail
white_horse2040@yahoo.com
Thanks
gaurav dubey
July 29th, 2009 at 9:47 am
51I have used this example and it works like a charm.
But there is one problem.If I type “r”(lowercase) then it works fine, but if I type “R” there is no suggestions.
Sathish
October 21st, 2009 at 2:47 pm
52Hi, Your code is very useful, i used database instead of array and now i need to filter with respect to another field in the form, can u guide me pls?
kurshom
October 27th, 2009 at 11:47 am
53How i retrieve data from data base not from array, please help
Kris
October 29th, 2009 at 4:59 pm
54Looks good, but strange thing happened.
It requires data in format:
[”item1″,”item2″,…]
and JSON is something like:
{0:”item1″,1:”item2″,…}
Is this a bug or it should be that way?
güzel kızlar
November 12th, 2009 at 1:31 pm
55Thanks
mark
January 7th, 2010 at 5:37 pm
56Thanks! This is a really simple implementation and was exactly what I was looking for. Thanks so much!
Peter Abolins
January 14th, 2010 at 4:03 pm
57Hi fromvega,
Did you ever complete the multiple input-field auto-complete version (pun intended)? I am modifying a website that used your initial plug-in and if there was indeed an updated version of your plug-in, it would save some work.
If not, that is okay - I’ll write my own. Duplicating code (as was suggested for multiple fields) is for script-kiddies - not for programmers
RSS feed for comments on this post · TrackBack URI
Leave a reply