Creating a simple auto suggest
Hello everyone. After a long time i posting this new tutorial. I created it for my friend who needed this auto suggest feature. This is a simple feature that can be used when u need to type city, so you can suggest previously saved cities.
Even can be used where you need to put suggestion for search keywords, names, places etc.
Let’s start… first you need to create an index page with a field
1 2 3 4 5 6 7 8 9 10 11 12 13
<input type="text" name="text" onkeyup="getAutoSuggest(document.getElementById('key'))" id="key">
<!-- and yes the auto suggest box-->
<div id="autobox">
<ul>
</ul>
</div>
as u can see there is a function called up on key up. This function takes the input text and calls a php file that uses the input to display results.
The function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
function getAutoSuggest(element) //---- a global common function to call sub categories
{
string = element.value
var dataString = 'text='+string; // sending the category id
//alert(dataString);
jQuery.ajax({
type: "POST",
url: "getList.php", //--the file to call--
data: dataString,
cache: false,
success: function(html)
{
if(html != "")
{
jQuery('#autobox ul').empty();
jQuery('#autobox ul').append(html);// appending to the auto-suggest box
jQuery('#autobox').slideDown();
return false;
}
else
{
jQuery('#autobox ul').empty();
jQuery('#autobox').slideUp();
return false;
}
}
});
return false;
}
The php file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
<?php
$string = $_POST['text'];//-- id got via post--
/*
* run the sql and generate the result in the format below
*/
if($string!="")
{
for($x=0;$x<=5;$x++)//
{
?>
<li id="pro<?=$x?>" onclick="setValue(<?=$x?>)">
String = "<?=$string?>" Click to set value as <?=$x?>
</li>
<?
}
}
// as u can see the LI generated calls a function "setValue"
?>
The “setValue ” function takes the value parameter and when u click on the result generated, its closes the the suggestion box and saves the value in the textbox.
1 2 3 4 5 6 7 8 9 10 11
function setValue(value)
{
jQuery('#autobox ul').empty();
jQuery('#autobox').slideUp();
jQuery('[name = text]').val(value);
}
thats all and yeah some styling too
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#autobox
{
background-color: #FFFDF7;
border: #EDED00 1px solid;
}
#autobox ul li
{
list-style: none;
cursor: pointer;
padding: 3px;
}

