Here we are going to discuss about implement a auto-complete feature using jQuery
<script type=”text/javascript” src=”jquery.js” mce_src=”jquery.js”></script>
<script type=”text/javascript” src=”dimensions.js” mce_src=”dimensions.js”></script>
<script type=”text/javascript” src=”autocomplete.js” mce_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:
the id of the input field
the id of the div that will hold the returned data
the URL of the remote script that will process the request
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” mce_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!