Ajax to automatically complete the form field example, ajax to complete the field example

Source: Internet
Author: User

Ajax to automatically complete the form field example, ajax to complete the field example

Source code:

Script 1:

<!DOCTYPE html>

Script 2:

body, #searchfield {font: 1.2em arial, helvetica,sans-serif;}.suggestions {background-color: #FFF;padding: 2px 6px;border: 1px solid #000;}.suggestions:hover {background-color: #69F;}#popups {position: absolute;}#searchField.error {background-color: #FFC;}

Script 3:

window.onload = initAll;var xhr = false;var statesArray = new Array();function initAll() {document.getElementById("searchField").onkeyup = searchSuggest;if (window.XMLHttpRequest) {xhr = new XMLHttpRequest();}else {if (window.ActiveXObject) {try {xhr = new ActiveXObject("Microsoft.XMLHTTP");}catch (e) { }}}if (xhr) {xhr.onreadystatechange = setStatesArray;xhr.open("GET", "us-states.xml",true);xhr.send(null);}else {alert("Sorry, but I couldn't create an XMLHttpRequest");}}function setStatesArray() {if (xhr.readyState == 4) {if (xhr.status == 200) {if (xhr.responseXML) {var allStates = xhr.responseXML.getElementsByTagName("item");for (var i=0; i<allStates.length; i++) {statesArray[i] = allStates[i].getElementsByTagName("label")[0].firstChild;}}}else {alert("There was a problem with the request " + xhr.status);}}}function searchSuggest() {var str = document.getElementById("searchField").value;document.getElementById("searchField").className = "";if (str != "") {document.getElementById("popups").innerHTML = "";for (var i=0; i<statesArray.length;i++) {var thisState = statesArray[i].nodeValue;if (thisState.toLowerCase().indexOf(str.toLowerCase())== 0) {var tempDiv = document.createElement("div");tempDiv.innerHTML = thisState;tempDiv.onclick = makeChoice;tempDiv.className = "suggestions";document.getElementById("popups").appendChild(tempDiv);}}var foundCt = document.getElementById("popups").childNodes.length;if (foundCt == 0) {document.getElementById("searchField").className ="error";}if (foundCt == 1) {document.getElementById("searchField").value = document.getElementById("popups").firstChild.innerHTML;document.getElementById("popups").innerHTML = "";}}}function makeChoice(evt) {if (evt) {var thisDiv = evt.target;}else {var thisDiv = window.event.srcElement;}document.getElementById("searchField").value = thisDiv.innerHTML;document.getElementById("popups").innerHTML = "";}

The analysis is as follows:

1. Please enter your state: <br>
<Input type = "text" id = "searchField" autocomplete = "off"> <br>
<Div id = "popups"> </div>
This is the HTML code we should pay attention. The special feature is the autocomplete attribute (which is non-standard compatible ).
It tells the browser not to execute any auto-completion on this field, because we will use scripts to process auto-completion. And XMLHttp-
Request is the same. Although autocomplete is not part of any W3C recommendation, it is well supported across browsers.
2. document. getElementById ("searchField"). onkeyup = searchSuggest;
To capture and process keys, an event handler is required, which is set in initAll.
3. xhr. onreadystatechange = setStatesArray;
Xhr. open ("GET", "us-states.xml", true );
Xhr. send (null );

4.

if (xhr.responseXML) {var allStates = xhr.responseXML.getElementsByTagName("item");for (var i=0; i<allStates.length; i++) {statesArray[i] = allStates[i].getElementsByTagName("label")[0].firstChild;}}

Here we read the file, view each item node, find the label node, and store the firstChild
(State name itself ). Each state name is stored in an element in the statesArray.
5. var str = document. getElementById ("searchField"). value;
Document. getElementById ("searchField"). className = "";
When the field is input, the code in the searchSuggest () event handler is executed. First obtain
The value of searchField, that is, the information that has been input so far. Next, clear the class attribute of this field.

6. if (str! = ""){
Document. getElementById ("popups"). innerHTML = "";
If you have not entered any information, do not do anything. Therefore, check here to make sure that the user has entered a value,
Then, a list of possible values is displayed. If you have already entered some information, clear the list of possible values.
7. for (var I = 0; I <statesArray. length; I ++ ){
Var thisState = statesArray [I]. nodeValue;
Now, traverse the list of state names and store the currently viewed State names in thisState.
8. if (thisState. toLowerCase (). indexOf (str. toLowerCase () = 0 ){
We want to check whether the user has entered a part of a certain State name so far-but this is not enough.
Make sure that the entered content is at the beginning of the state name. After all, if you enter Kansas, you do not want to display Arkansas in the drop-down list
Or Kansas. In addition, make sure that both strings are in lower case before checking indexOf.
If indexOf () returns 0 (that is, the input string is found at the beginning of thisState), then we
You will find a match.
9.

var tempDiv = document.createElement("div");tempDiv.innerHTML = thisState;tempDiv.onclick = makeChoice;tempDiv.className = "suggestions";document.getElementById("popups").appendChild(tempDiv);

Because this state name is a possible value, we want to add it to the list to be displayed. The implementation method is to create a temporary
To set its innerHTML to the state name, add the onclick handler and className, and then chase the entire div
Add to popups div. Add each State name as a separate div so that we can use JavaScript and CSS to operate each
State name.
10. var foundCt = document. getElementById ("popups"). childNodes. length;
After traversing all the State names, we will create a pop-up window -- but how many State names do we get? Calculate
Value: foundCt.
11. if (foundCt = 0 ){
Document. getElementById ("searchField"). className = "error ";
}
If the foundCt value is 0, it indicates that the user entered the incorrect content. We set className to error, so that users can
Knowing that the input is incorrect, this setting will make the input field show a light yellow background (this is controlled by the CSS style rules in script 13-17 ).
12.

if (foundCt == 1) {document.getElementById("searchField").value = document.getElementById➝("popups").firstChild.innerHTML;document.getElementById("popups").innerHTML = "";}

If foundCt is 1, we know that a unique match is found, so we can put this state name into the field. If the user has
After entering ca, they do not need to enter lifornia, because we already know which state they want to enter. We use
Enter the input field for the unique div in popups to automatically provide the complete state name, and then clear the popups div.
13.

 function makeChoice(evt) {if (evt) {var thisDiv = evt.target;}else {var thisDiv = window.event.srcElement;}document.getElementById("searchField").value = thisDiv.innerHTML;document.getElementById("popups").innerHTML = "";}

Another way to enter the state name is to click a state name in the pop-up list. In this case, makeChoice () is called.
Processing Program. First, we check the event Target to find out which state the user has clicked. This provides a specific div.
The innerHTML of this div provides the State name. We put this state name in the input field. Finally, the pop-up of clearing possible values
List.


Ajax for google auto-completion

Auto-completion should not be determined after you press Enter. It should be determined that when you press the key, you will start to judge that when you enter Chinese, you will not hit the text box when you press the pinyin word. At this time, this event does not exist. trigger. Therefore, you do not need to press enter to determine whether there is automatic completion. Each input character will send a request. before sending the request, you should clear the text box and determine whether the backspace key should be used to automatically complete the request.

Ajax auto-completion

Your input box must be <input>. The input has an onchange event. When the value in the text box changes, the onchange event is triggered. You can write a method in this event, use ajax to check in the background

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.