Ajax Implementation text box input automatic prompt function

Source: Internet
Author: User

I think any gorgeous effect is driven by customers, because customers always want to spend the least amount of money to buy the best software, just like we always want to spend the least amount to buy the best goods. This week, the bully's clients have been very kind to me to develop a new feature, because their bosses like this thing. I faint, you do this software is to please your superiors. Development on the development of it, do not write point code.

The so-called text box input automatic prompt, is refers to enter a character in the text box, prompted with the corresponding list of characters, in order to facilitate the user to choose, show the effect chart first:

How, is not very beautiful. I think I have a good grounding in art, haha. A discerning eye can see, this with Baidu and Google input hint is very similar, yes, I am the model to visit the two Internet giants effect. Here is a concrete step:

First, write JavaScript, engage in web development, JS is kingly:

   /** * Input Accessibility component This component wrote I think it is OK, if you need to modify this component, please be careful to change, or change can not be used and I am not in the scene, it is difficult to do. * * @type/var assistinput = {li_index:-1, init:function (input, URL) {//support Firefox var event = window.event | | argu Ments.callee.caller.arguments[0]; var keyasc = Event.keycode; Invoke server-side methods from numbers to characters, backspace, and delete keys (keyasc >= && keyasc <=) | | keyasc = 8 | | keyasc = +) {Assistinput.find Userbyajax (input, URL); else {assistinput.lightmove (KEYASC);}}, Finduserbyajax:function (input, url) {var assistparent = Input.offsetparent ; var str = input.value; Filedname = Input.name; var par = "str=" + str; var json = null; New Ajax.request (URL, {method: ' Post ', Parameters:par, oncomplete:function (response) {var text = Response.responset Ext JSON = eval ("(+ text +)"); if (JSON!= null) {var mydiv = document. getElementById ("Assistinputdiv"); assistinput.setdivposition (input);//Set div position var ul = Assistinput.setul (JSON, input); mydiv.innerhtml = ul; MyDiv.style.display = "BloCK "; } } }); }, Lightmove:function (KEYASC) {var li = document.getElementById ("Assistinputdiv"). getElementsByTagName ("Li"); if (key ASC = = = {if (assistinput.li_index!=-1) {//revert to original color li[assistinput.li_index].classname = "";} assistinput.li_index++; If the last element is made, the first if (Assistinput.li_index = = li.length) {assistinput.li_index = 0;}//Change style Li[assistinput.li_index ].classname = "Input_assist"; if (Keyasc = = 38) {//up//Not equal to-1, index self-subtraction if (Assistinput.li_index!=-1) {//revert to original color Li[assistinput.li_index].classnam e = ""; assistinput.li_index--; //equal to-1, move the index to the last if (Assistinput.li_index = 1) {assistinput.li_index = li.length-1;} li[assistinput.li_index].cl Assname = "Input_assist"; } if (Keyasc = = 13) {//Carriage return//Call Set Value method Assistinput. Fillassistinputtext (Filedname, Li[assistinput.li_index]);},//set UL s Etul:function (JSON, input) {if (json = = Undefined | | json = = = "") {return;} var ul = "<ul class= ' ul_background ' style= ' width:" + AssistInputDiv.style.widtH + "' >"; For (var index in JSON) {var userobject = Json[index]; var name = userobject["Name"; var filedvalue = userobject["id"]; if (name = = = undefined) {Continue} else {if (index = = 0) {ul = ' <li class= ' input_assist ';} else {ul = ' <li "; } UL = + "id=" + filedvalue + "style=" List-style-type:none; "mce_style=" List-style-type:none; "onmouseover=" Assistinput.changecss (assistinput) ' onclick= ' Assistinput.fillassistinputtext (/"" + Input.id + "/", AssistInput) ' > "+ name + </li>";}} UL = "</ul>"; return ul; },//set div coordinates setdivposition:function (assistinput) {var assisthiddendiv = document.getElementById ("Assistinputdiv"); /Get the height, width, margin of the text box var offsetleft = Assistinput.getboundingclientrect (). Left + Document.documentElement.scrollLeft; var offsettop = Assistinput.getboundingclientrect (). Top + document.documentElement.scrollTop + 19; var offsetwidth = assistinput.offsetwidth; Set the properties of the div assistHiddenDiv.style.width = offsetwidth; Assisthiddendiv.style. left = Offsetleft; AssistHiddenDiv.style.top = offsettop; },//Set the value of the text box fillassistinputtext:function (assistinputtext, obj) {var assistinput = document.getElementById ( Assistinputtext); Assistinput.value = Obj.innertext; var filedid = assistinputtext.substring (0, Assistinputtext.length-//5); Document.getelementsbyname (filedid) [0].value = Obj.id; AssistInputDiv.style.display = "None"; /////change Li's css changecss:function (obj) {var assisthiddendiv = document.getElementById ("Assistinputdiv") when the mouse moves. Geteleme Ntsbytagname ("Li"); var length = Assisthiddendiv.length; for (var i in assisthiddendiv) {assisthiddendiv[i].classname = "";} Obj.classname = "Input_assist"; }/** * Main function * @param {} input needs to be auxiliary input tag object * @param {} URL to service side of URL to provide secondary data/function main (input, url) {var assis Tinputobj = new Assistinput.init (input, URL); }

As you can see, I used the AJAX framework of prototype to submit data, why use Ajax. Because we want to do the effect is no brush effect, the user input a word, it is necessary to query from the database, and then the query data returned to the client, and then through the DOM operation to display to the user, this is our basic ideas. We also need to handle the keyboard response event, for example, the user presses the ↑↓ two arrows, we need to change the corresponding Li background color red, of course, you want to use any color can be. In addition, the mouse to enter and move out of the event, with up and down arrows processing is similar. There's also a pretty important key that you might have thought of, that's the return return, when we hit enter, you should set the selected file to the text box.

Second, the preparation of style files, Web development CSS is also plays:

. input_assist {background-color:red}. ul_background {background-color:blue; margin-left:-40px; margin-top:-1px; List-style-type:none; }

I am not, only use the blue and red background color, of course, this is just my demo, the actual project code can not be posted, or I will lose money.

Third, the preparation of JSP page:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

Wait a minute. NET programmer do not hit me, you can fully use ASP to achieve, but I am a Java programmer, can not. NET to make any account.

Four, provide a service-side CGI program

Now software development has basically no CGI this term, but, whether the servlet or struts in the action, is based on this principle, I used the webwork framework, I put a single action here, the other configuration depends on your own.

 package com.boc.demo.action; Import java.util.ArrayList; Import java.util.List; Import Javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.HttpServletResponse; Import Net.sf.json.JSONArray; Import Com.boc.demo.pojo.Test; Import Com.opensymphony.webwork.ServletActionContext; Import com.opensymphony.xwork.Action; public class Testaction implements Action {private string name; public string execute () throws Exception {Httpservletreq Uest request=servletactioncontext.getrequest (); HttpServletResponse Response=servletactioncontext.getresponse (); Response.setcharacterencoding ("UTF-8"); list<test> list = new arraylist<test> (); for (int i = 0; i < 5; i++) {test test = new test (); Test.setid (i + ""); Test.setname ("Zhang 33" + i); List.add (test); } jsonarray Jsonary=jsonarray.fromobject (list); Response.getwriter (). print (jsonary); Test.setname (name); Testservice ts = new Testservice (); Ts.add (test); return null; Public String GetName () {return name;} PUBlic void SetName (String name) {this.name = name;}}

Five, this example is finished, for more Ajax effects, please continue to pay attention to my blog, the dead of night, I also want to sleep ...

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.