Ajax automatic prompt Function

Source: Internet
Author: User

Net. js file content:
VaR net = new object ();
Net. contentloader = function (URL, PostBack, Params)
{
This. url = URL;
This. PostBack = PostBack;
This. Params = Params;
This. Req = NULL;
This. loadxmldoc (URL );
}

Net. contentloader. Prototype =
{
Createxmlhttprequest: function ()
{
If (window. XMLHttpRequest)
{
This. Req = new XMLHttpRequest ();
}
Else if (window. activexobject)
{
VaR arrversions = ["msxml2.xmlhttp. 5.0", "msxml2.xmlhttp. 4.0", "msxml2.xmlhttp. 3.0 ",
"Msxml2.xmlhttp", "Microsoft. XMLHTTP"];
For (VAR I = 0; I <arrversions. length; I ++)
{
Try
{
This. Req = new activexobject (arrversions [I]);
}
Catch (oerror)
{}
}
}
Return this. req;
},

Loadxmldoc: function (URL)
{
If (this. createxmlhttprequest ())
{
Try
{
VaR othis = this;
This. Req. onreadystatechange = function ()
{

Othis. onreadystate. Call (othis );
// Loader. onreadystate ();
}
This. Req. Open ("Post", URL, true );
This. Req. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
This. Req. Send (this. Params );
}
Catch (oerror)
{}
}
},

Onreadystate: function ()
{
If (this. Req. readystate = 4)
{
If (this. Req. Status = 200 | this. Req. Status = 0)
{
This. PostBack. Call (this );
// This. PostBack ();
}
}
}

}
Main. js file content:
Window. onload = function ()
{
VaR elemspan = Document. createelement ("span ");
Elemspan. ID = "spanoutput ";
Elemspan. classname = "spantextdropdown ";
Document. Body. appendchild (elemspan );
Document.form1.txt userinput. OBJ = setproperties(document.form1.txtuserinput,document.form1.txt uservalue,
"Typeaheaddata. aspx", true,
"No matching data! ", False, null );

}

Function setproperties (xelem, xhidden, xservercode, xignorecase, xmatchanywhere,
Xmatchtextboxwidth, xshownomatchmessage, xnomatchingdatamessage,
Xusetimeout, xthevisibletime)
{
VaR props =
{
ELEM: xelem,
Hidden: xhidden,
Servercode: xservercode,
Regexflags :( (xignorecase )? "I ":""),
Regexany :( (xmatchanywhere )? "": "^ "),
Matchanywhere: xmatchanywhere,
Matchtextboxwidth: xmatchtextboxwidth,
Thevisibletime: xthevisibletime,
Shownomatchmessage: xshownomatchmessage,
Nomatchingdatamessage: xnomatchingdatamessage,
Usetimeout: xusetimeout
};
Addhandler (xelem );
Return props;
}

VaR isopera = (navigator. useragent. tolowercase (). indexof ("Opera ")! =-1 );

Function addhandler (objtext)
{
Objtext. onkeyup = giveoptions;
Objtext. onblur = function ()
{
If (this. obj. usetimeout)
{
Starttimeout ();
}
}
If (isopera)
{
Objtext. onkeypress = giveoptions;
}
}

// Global variable
VaR arroptions = new array ();
VaR strlastvalue = "";
VaR bmaderequest;
VaR thetextbox;
VaR objlastactive;
VaR currentvalueselected =-1;
VaR bnoresults = false;
VaR istiming = false;

Function giveoptions (Event)
{
VaR Ikey =-1;
If (window. Event)
{
Ikey = Window. event. keycode;
Thetextbox = Window. event. srcelement;
}
Else
{
Ikey = event. Which;
Thetextbox = event.tar get;
}

If (thetextbox. obj. usetimeout)
{
If (istiming)
{
Erasetimeout ();
}
Starttimeout ();
}

If (thetextbox. value. Length = 0 &&! Isopera)
{
Hidethebox ();
Strlastvalue = "";
Return false;
}

If (objlastactive = thetextbox)
{
If (Ikey = 13)
{
Grabhighlighted ();
Thetextbox. Blur ();
Return false;
}
Else if (Ikey = 38)
{
Movehighlight (-1 );
Return false;
}
Else if (Ikey = 40)
{
Movehighlight (1 );
Return false;
}
}

// Query idea:
// 1. If the content of this query only adds some content after the last text, first determine if the last query has results,
// Extract the result from the cache. If there is no result in the buffer, send a request to the server.
// 2. If no result is returned for the last query, and the input content is added only after the last text, it will not be processed;
// 3. In other cases, submit a request to the server to obtain new data.
If (thetextbox. value. indexof (strlastvalue) = 0) & (strlastvalue! = ""))
{
If (! Bnoresults)
{
Buildlist (thetextbox. value );
If (bnoresults)
{
Objlastactive = thetextbox;
Bmaderequest = true;
Typeahead (thetextbox. value );
}
}
}
Else
{
Objlastactive = thetextbox;
Bmaderequest = true;
Typeahead (thetextbox. value );
}
// Display information
Showmessage ();
Strlastvalue = thetextbox. value;
}

Function typeahead (xstrtext)
{
VaR strparams = "q =" + xstrtext + "& where =" + thetextbox. obj. matchanywhere;
VaR loader = new net. contentloader (thetextbox. obj. servercode, buildchoices, strparams );
}

Function buildchoices ()
{
VaR strtext = This. Req. responsetext;
Eval (strtext );
Buildlist (strlastvalue );
Bmaderequest = false;
}

Function buildlist (thetext)
{
Setelementposition (thetextbox );
VaR thematches = makematches (thetext );
Thematches = thematches. Join (). Replace (//,/GI ,"");
If (thematches. length> 0)
{
Document. getelementbyid ("spanoutput"). innerhtml = thematches;
Document. getelementbyid ("optionslist_0"). classname = "spanhighelement ";
Currentvalueselected = 0;
Bnoresults = false;
}
Else bnoresults = true;
}

Function showmessage ()
{
If (bnoresults)
{
Currentvalueselected =-1;
Bnoresults = true;
If (thetextbox. obj. shownomatchmessage)
{
Document. getelementbyid ("spanoutput"). innerhtml =
"<SPAN class = 'nomatchdata'>" + thetextbox. obj. nomatchingdatamessage + "</span> ";
}
Else hidethebox ();
}
}

Function setelementposition (thetextboxinput)
{
VaR selectedposx = 0;
VaR selectedposy = 0;
VaR theelement = thetextboxinput;
If (! Theelement) return;
VaR theelemheight = theelement. offsetheight;
VaR theelemwidth = theelement. offsetwidth;
While (theelement! = NULL)
{
Selectedposx + = theelement. offsetleft;
Selectedposy + = theelement. offsettop;
Theelement = theelement. offsetparent;
}
Xposelement = Document. getelementbyid ("spanoutput ");
Xposelement. style. Left = selectedposx;
If (thetextboxinput. obj. matchtextboxwidth)
{
Xposelement. style. width = theelemwidth;
}
Xposelement. style. Top = selectedposy + theelemheight;
Xposelement. style. Display = "Block ";
If (thetextboxinput. obj. usetimeout)
{
Xposelement. onmouseout = starttimeout;
Xposelement. onmouseover = erasetimeout;
}
Else
{
Xposelement. onmouseout = NULL;
Xposelement. onmouseover = NULL;
}
}

VaR countforid = 0;
Function makematches (xcomparestr)
{
Countforid = 0;
VaR matcharray = new array ();
VaR Regexp = new Regexp (thetextbox. obj. regexany + xcomparestr, thetextbox. obj. regexflags );
For (VAR I = 0; I <arroptions. length; I ++)
{
VaR thematch = arroptions [I] [0]. Match (Regexp );
If (thematch)
{
Matcharray [matcharray. Length] = createunderline (arroptions [I] [0], xcomparestr, I );
}
}
Return matcharray;
}

VaR undestart = "<SPAN class = 'spanmatchtext'> ";
VaR undeend = "</span> ";
VaR selectspanstart = "<span style = 'width: 100%; display: block; 'class = 'spannormalpart'" +
"Onmouseover = 'sethighcolor (this )'";
VaR selectspanend = "</span> ";

Function createunderline (xstr, xtextmatch, xval)
{
Selectspanmid = "onclick = 'settext (" + xval + ") '"+" id = 'optionslist _ "+ countforid +" 'thearraynumber =' "+ xval +" '> ";
VaR Regexp = new Regexp (thetextbox. obj. regexany + xtextmatch, thetextbox. obj. regexflags );
VaR astart = xstr. Search (Regexp );
VaR matchedtext = xstr. substring (astart, astart + xtextmatch. Length );
Countforid ++;
Return selectspanstart + selectspanmid + xstr. Replace (Regexp, undestart + matchedtext + undeend) + selectspanend;
}

Function movehighlight (xdir)
{
If (currentvalueselected> = 0)
{
Newvalue = parseint (currentvalueselected) + parseint (xdir );
If (newvalue>-1 & newvalue <countforid)
{
Currentvalueselected = newvalue;
Sethighcolor (null );
}
}
}

Function sethighcolor (thetextbox)
{
If (thetextbox)
{
Currentvalueselected = thetextbox. Id. Slice (thetextbox. Id. indexof ("_") + 1, thetextbox. Id. Length );
}
For (VAR I = 0; I <countforid; I ++)
{
Document. getelementbyid ("optionslist _" + I). classname = "spannormalelement ";
}
Document. getelementbyid ("optionslist _" + currentvalueselected). classname = "spanhighelement ";
}

Function settext (xval)
{
Thetextbox. value = arroptions [xval] [0];
Thetextbox. obj. Hidden. value = arroptions [xval] [1];
Document. getelementbyid ("spanoutput"). style. Display = "NONE ";
Currentvalueselected =-1;
}

Function grabhighlighted ()
{
If (currentvalueselected> = 0)
{
Xval = Document. getelementbyid ("optionslist _" + currentvalueselected). getattribute ("thearraynumber ");
Settext (xval );
Hidethebox ();
}
}

Function hidethebox ()
{
Document. getelementbyid ("spanoutput"). style. Display = "NONE ";
Currentvalueselected =-1;
Erasetimeout ();
}

Function erasetimeout ()
{
Cleartimeout (istiming );
Istiming = false;
}

Function starttimeout ()
{
Istiming = setTimeout ("hidethebox ()", thetextbox. obj. thevisibletime );
}
Homepage.htm file content:
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> Ajax automatically completes the text box instance </title>
<LINK rel = "stylesheet" href = "main.css"/>
<SCRIPT type = "text/JavaScript" src = "net. js"> </SCRIPT>
<SCRIPT type = "text/JavaScript" src = "Main. js"> </SCRIPT>
</Head>
<Body>
<Form name = "form1" AutoComplete = "off" id = "form1" Action = "">
<Label> automatically complete text box: </label> <input type = "text" name = "txtuserinput"/>
<Input type = "hidden" name = "txtuservalue" id = "hidden1"/>
<Input type = "text" name = "txtignore" style = "display: none"/>
</Form>
</Body>
</Html>
Content of the typeaheaddata. aspx. CS file:
Using system;
Using system. Data;
Using system. configuration;
Using system. collections;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. Data. sqlclient;

Public partial class typeaheaddata: system. Web. UI. Page
{
Protected void page_load (Object sender, eventargs E)
{
Response. contenttype = "text/html ";
String strquery = request. Form. Get ("Q"). tostring ();
String strany = "";
If (request. Form. Get ("where"). tolower (). Equals ("true "))
{
Strany = "% ";
}

String strsql = "select top 15 productname, productid from products where productname" +
"Like '" + strany + strquery + "%" + "'order by productname ";
Datatable dtquestions = filldatatable (strsql );
System. Text. stringbuilder strjsarr = new system. Text. stringbuilder ();
Strjsarr. append ("arroptions = new array (");
Int icount = 0;
Int A = dtquestions. Rows. count;
Foreach (datarow row in dtquestions. Rows)
{
If (icount> 0)
{
Strjsarr. append (",");
}
Strjsarr. append ("[");
Strjsarr. append ("/" "+ row [" productname "]. tostring () + "/",");
Strjsarr. append ("/" "+ row [" productid "]. tostring () + "/"");
Strjsarr. append ("]");

Icount ++;
}
Strjsarr. append (");");
Response. Write (strjsarr. tostring ());
}

Public datatable filldatatable (string strquery)
{
String strconn = "Server = localhost; database = northwind; uid = sa; Pwd = ;";
Dataset DS = new dataset ();
New sqldataadapter (strquery, strconn). Fill (DS );
Return Ds. Tables [0];
}
}
Content of the typeaheaddata. aspx file:
<% @ Page Language = "C #" autoeventwireup = "true" codefile = "typeaheaddata. aspx. cs" inherits = "typeaheaddata" %>
Main.css file content:
Span. spantextdropdown
{
Position: absolute;
Top: 0px;
Left: 0px;
Width: 150px;
Z-index: 101;
Background-color: # c0c0c0;
Border: 1px solid #000000;
Padding-left: 2px;
Overflow: visible;
Display: none;
}

Span. spanmatchtext
{
Text-Decoration: underline;
Font-weight: bold;
}

Span. spannormalelement
{
Background: # c0c0c0;
}

Span. spanhighelement
{
Background: #909af4;
Color: white;
Cursor: pointer;
}

Span. nomatchdata
{
Font-weight: bold;
Color: # 0000ff;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.