Find as you type - 2
The tutorial accompanies demo and examples at AJAX AUTOCOMPLETE EXAMPLE
Autocomplete Javascript for finding as you type has comments which should be self explanatory.
Rather than making AJAX Calls on every key press what we are doing is we are getting a large number of data. So for "Wh" we will get all the blog title which have "what", "why", "which", "where" etc. So on further key press we search first locally refining our results. Once no results are found locally we again make an AJAX Call and again get large results. The process continues like this till 4 AJAX Calls. If even after that we do not find any matches locally or at server then we assume that there is no data with such typed text. This caching and restricting AJAX calls to autocomplete will restrict large usage of your website bandwidth and better results with more text being send between each AJAX calls and hence better results.
<script type="text/javascript">
//Declare some global variables
//"recarray" is an array which will hold all the data returned from server by AJAX call
var recarray = new Array();
//"chosen" will store the highlighted option position by the arrow key
var chosen="";
//"opt_no" stores the highlighted options number by the arrow key
var opt_no= new Array();
//"searching" is a boolean which will tell whether an AJAX call is already in progress
var searching;
//"nothing" is a boolean checking if server has anything to return as data
var nothing = false;
//"before" will hold the previous value entered in the textbox e.g. the value less the last character
var before ="";
//"no_time" will hold the number of AJAX calls made.
var no_time =0;
function shownothing(x){
//If there is no matched data locally or from server then show the below divs
$("dropdown").innerHTML='<span id="showid_-1" class="hide">' x '</span><span id="valid_-1" class="hide">-1</span><div
class="dt" id="opt_-1" onclick=setvalue("-1"); onmouseover="removed();">' x '</div>';
}
//"allok" is a function used in the AJAX call and is used once the AJAX call is completed
//Using this function you can decide what to do with the returned data from the AJAX Call
//The function forms the 4th optional part of the AJAX calls.
function allok(to_show,to_modify){
//to_show holds the AJAX returned data
//to_modify holds the text entered in the text-box
the_value=to_modify;
//If the server has nothing to show
if(to_show =='<span class="errors">Nothing Found</span>')
{
//set "nothing" to true
nothing=true;
//Increase the count of "no_time"
no_time ;
//activate the "shownothing" function
shownothing(the_value);
if (no_time > 3){nothing=false;}
}
else{
//Received data to be formatted - split the data into array where the string has "***"
recarray = to_show.split("***");
//Call the "listing" function with the typed text
listing(the_value);
}
//Set the searching to false indicating AJAX call ended
searching = false;
}
//This function will remove the highlighted option selected by the arrow key
function removehighlight(theClass){
//Get all the elements with tag "div" in the element "dropdown"
allHTMLTags=$("dropdown").getElementsByTagName("div");
//Of the got tags change the class name to "dt" whose previous class name was as defined
for(i=0;i<allHTMLTags.length;i ){if(allHTMLTags[i].className==theClass){allHTMLTags[i].className="dt";}}
}
function aj_call(the_str,thevalue){
//Make the AJAX Call
//Send the data to the PHP page "aj_autocomplete-example.php"
//The returned data will be displayed in the div with id "dropdown"
//While the AJAX data is send/received keep the user informed with text "autocompleting.."
//4th parameter "thevalue" if set will use the function "allok" once data is received after AJAX call as defined before
callAHAH("aj_autocomplete-example.php?" the_str,"dropdown","autocompleting..",thevalue);
//Set the searching to true indicating AJAX call in progress
searching = true;
}
//This function gets activated at every keyup.
function ajax_autocomplete(thevalue,e){
//Do not show the dropdown if less than 3 digits also reset every variable and do nothing
if(thevalue.length < 3){recarray =new Array();dontshow("dropdown");before ="";searching=false;nothing=true;no_time=0;return false;}
//detect which key was pressed
var action = e.which;
//detect which key was pressed for IE
if (action == undefined){action = e.keyCode;}
//If Backspace was pressed, check the value with the "listing" function
if (action == 8){listing(thevalue);return false;}
//If delete was pressed, check the value with the "listing" function
if (action == 46){listing(thevalue);return false;}
//If arrow down was pressed then highlight the option
if(action == 40){highlight(1);return false;}
//If arrow up was pressed then highlight the option
if(action == 38){highlight(-1);return false;}
//If enter was pressed
if(action == 13){
//if option was highlighted and pressed enter
if(chosen !==-1)
{
//if option was highlighted and pressed enter
if(chosen !==-1)
{
//Fill the text-box with the value
$("autocomplete_value").value = $("showid_"+opt_no[chosen]).innerHTML;
//Fill the text-box with the ID
$("thetxtid").value = $("valid_"+opt_no[chosen]).innerHTML;
//hide the autocomplete dropdown div
dontshow("dropdown");
//Also change the highlighted option to default with no highlight
chosen = -1;
//no need to go ahead
return false;
}
}
//If it is not a character key then do nothing
if (action < 32 || (action >= 33 && action <= 46) || (action >= 112 && action <= 123)){return false;}
//else make the ajax call
else {
//If the searching is not set it indicates no AJAX Call in progress
//If the previous value is not one less then the present value
//If nothing is found either after matching locally or after the AJAX call
if(!searching && (thevalue.indexOf(before) != 0 || nothing))
{
//Change the "dropdown" class to "show" and unhide the same
$("dropdown").className="show";
//Get string detail to send by AJAX call
var t_str="p=6&m=" thevalue ;
//Make the AJAX call by the function "aj_call"
aj_call(t_str,thevalue);
}
else {
//else use the listing function with the text in the textbox
listing(thevalue);
}
//Set "before" to the typed text value in the textbox
before=thevalue;
//If any previous selection done from the options then reset that
if($("thetxtid").value!==""){$("thetxtid").value="";}
}
}
//"matcheddata" will return all the AJAX returned data which matches the typed text in the textbox
function matcheddata(thestr){
//Using regular expression we assign the pattern to find e.g. "thestr". i will ignore the caps
regExp = new RegExp(thestr,"i");
var final=new Array();
//"recarray" is the received array found in the "allok" function after completion of AJAX call
//for each array data we need to split the value and the Id
for(i=0;i<recarray.length;i )
{
//Split again at "---" to separate ID and value - "recdata[0]" stores the ID and "recdata[1]" stores the value string
recdata=recarray[i].split("---");
//If "thestr" matches in the received AJAX returned value string
if(recdata[1].match(regExp)){
//return index of the first match between the regular expression and value string
var begin = recdata[1].search(regExp);
//return a substring of the value string that starts at "begin" and ends at the specified length
var matched = recdata[1].substring(begin,begin+thestr.length);
//return the new string that results after all matches of regex within and enclose with <b> and <u>
milgaya= recdata[1].replace(regExp,"<u><b>"+matched+"</b></u>");
//format the string with additional div containing value and Id and store it in an array "final"
final[i]='<span id="showid_' i '" class="hide">' recdata[1] '</span><span id="valid_' i '" class="hide">' recdata[0] '</span><div class="dt" id="opt_' i '" onclick=setvalue("' i '"); onmouseover="rhigh();">' milgaya;
}
}
//return the "final" array
return final;
}
//"listing" function checks locally if the input text matches strings from "recarray" array of AJAX call
function listing(theText){
//reset "chosen" to default value
chosen = -1;
//find number of matches found with the input text and the AJAX data returned
foundmatch = matcheddata(theText);
if(foundmatch.length > 0)
{
//if there are matches found, join them with the closing div and make it as a string
var stringshow=foundmatch.join("</div>");
//show the string thus made in the "dropdown" div
$("dropdown").innerHTML=stringshow;
//Since we have found something locally, "nothing" to be set "false"
nothing = false;
}
else{
//no matches found so "nothing" to be set "true"
nothing=true;
//However if more than 3 AJAX calls made then "nothing" to be set "false" to prevent more AJAX Calls
if (no_time > 3){nothing=false;}
//activate the "shownothing" function
shownothing(theText);}
}
//"highlight" function highlights the options when selected by the arrow keys
function highlight(x){
//Get all the elements with tag "div" in the element "dropdown"
allHTMLTags=$("dropdown").getElementsByTagName("div");
//Of the got tags get the id number of the options and store them in "opt_no" array at highlighted position
for(i=0;i
now=parseInt(chosen) parseInt(x);
//Get the total number of options returned after matching the text with the AJAX returned array "recarray"
var num=allHTMLTags.length;num--;
//While pressing arrow up key if the position reaches to end then default to 1st selection
if(now<=0){now=0;}
//While pressing arrow down key if the position reaches to end then default to last selection
if(now>num){now=num;}
//Also change the "chosen" value
chosen=now;
//remove any previous highlight of the option
removehighlight("marker");
//Highlight the option at the chosen position
$("opt_"+opt_no[now]).className="marker";
}
//This function activates when cursor is over any dropdown option
function rhigh(){
//When cursor is hovered over any option remove any previous highlighted option by arrow keys
removehighlight("marker");
//Also change the highlighted option to default with no highlight
chosen = -1;
}
//Hide any element by changing the class "hide". The CSS class "hide" has display:none and will not be shown
function dontshow(theid){$(theid).className="hide";}
//Select the highlighted text
function setvalue(num){
//Fill the text-box with the value
$("autocomplete_value").value = $("showid_" num).innerHTML;
//Fill the text-box with the ID
$("thetxtid").value = $("valid_" num).innerHTML;
//hide the autocomplete dropdown div
dontshow("dropdown");
//Also change the highlighted option to default with no highlight
chosen = -1;}
</script>
-
YOU MAY ALSO LIKE
- AJAX Autocomplete Tutorial
