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
32 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.
RSS feed for comments on this post · TrackBack URI
Leave a reply