9CBS - Document Center - JavaScript Read: 8074 Comments: 1 Participation in Reviews
Title with JavaScript to make an automatically fill-in text box (1) Select BLOG keywords from YJGX007 IE Opera Mozilla TextRange browser to detect http://www.sitepoint.com/Article/1220/ Copyright Notice: You can reprint, When reprint, you must indicate the original article in hyperlink http://xinyistudio.vicp.net/ and the author information and this statement (this article is suitable for the middle and advanced readers) Translating: In order to obtain more information, you do not hesitate to the website A large number of text boxes, menu, list boxes are generated in the page, when the user sees such a wide need to input or select items, which is likely to be bored and finally leaving your website. Using JavaScript for the input text box better design, avoid the above problems as much as possible, I hope this translation can help you in the development and design of the web page, the translation translation error is inevitable, and you will be criticized.
Today, people are most reluctant to face a lot of forms (form), especially those that need to be knocked into characters (that is, the HTML tag we often use, "later is called text box for convenience ). Microsoft combines the text box that automatically completes the input text box in Outlook - text box checks a small amount of characters entered by the user, then gives a suggested word from a given drop-down list. Similarly, when you start to fill in a URL address in the web address bar, your web browser will recommend a URL drop-down list.
In this tutorial, a little JavaScript control is used, we will create an input text box with IE (version 5.5 or higher) and Mozilla (version 1.0 or higher) browser.
Ø Simple browser detection ----------- First, we need to be a browser detection, below is some simple code (this process can be replaced by your own code) var isopra = Navigator.useragent.indexof ("Opera")> -1; var isie = Navigator.UserageRagent.indexof ("msie")> 1 &&! isopera; var ismoz = navigator.useragent.indexof ("mozilla / 5.") = = 0 &&! Isopera;
This code is obviously not very perfect, but it seems that it is enough for the purpose we have to achieve. Let's start this project.
Ø Select the text box ---------- The first step in this process is to create a method, this method can select the number of text in the text box. I will call this method TextBoxSelect (), it has three parameters, the first parameter is the object that makes this method acts: OTextBox; the second parameter is a non-must-have option, it indicates the selected start position (if this parameter is Ignore, then all texts are selected); the third parameter is the same, and the selection end position is indicated. If a second parameter is provided, the third parameter is not provided, and the text selected in the text box will come from the starting position to the end position. We write a very easy understanding: If there is only one parameter, then we use the prototype of the text box Select () in this text box to select all the text:
Function TextBoxSelect (OTEXTBOX, ISTART, IEND) {
Switch (arguments.length) {
Case 1:
OTextBox.select ();
Break;
...
}
}
Here we use the Switch statement test how many parameter inputs. If there is only one, only OTextBox is entered. Next, we jump to the beginning of the CASE statement of three parameters (iStart and Ind are selected). Here, we need to use a browser to detect everything to do, for the IE browser, we will use a text-range object.
Function TextBoxSelect (OTEXTBOX, ISTART, IEND) {
Switch (arguments.length) {
Case 1:
OTextBox.select ();
Break;
Case 3:
IF (isie) {
Var Orange = OtextBox.createTextRange ();
Orange.Movestart ("Character", iStart;
Orange.movend ("Character", -OTextBox.value.Length Iend;
Orange.select ();
} else if (ismoz) {
...
}
}
}
In the bold code, we started from a Text Range object (text-range object for text box object, TextRange sets the start and end coordinates of the text selection range, to adjust this to start coordinates We use movestart () method This method gives two parameters: parameter first is the mobile interval type, the code is used in the code; the parameter 2 is how many intervals are moved, such as moving 5 intervals, then the parameters One "character" learned to move 5 characters, if the parameter is "word", then move 5 words. (Translator Note: See MSDN for details on the method of the TextRange object). Movend () has the same parameters, slightly different is that its second parameter must be negative (translator Note: This parameter can be positive in MSDN2001, may be a positive number, may take into account the problem with the IE version), You can imagine whether you move to the end of the selected text, then return an interval, and then refund two intervals .... In order to obtain the second parameter of Movend (), we will assign a negative value of the length of text in the IEND text box, so if Iend is 8 and 10 characters in the text box, the second parameter becomes -2, select The range will return the end point back to 2 characters. Finally, we call the select () method to highlight the range in the text box. Complete the above thing for Mozilla browsers is actually easier to do. The text box object has a setSelectionRange () method, which has two parameters: the start and end position of the selected, you can use iStart and IEND settings directly:
function textboxSelect (oTextbox, iStart, iEnd) {switch (arguments.length) {case 1: oTextbox.select (); break; case 3: if (isIE) {var oRange = oTextbox.createTextRange (); oRange.moveStart ( " Character ", iStart); Orange.Movend (" Character ", -OxtextBox.value.Length Iend); Orange.Select ();} else if (ismoz) {OTextBox.setSelectionRange (iStart, IEND);}}}
Now we return to the last CASE statement, ie, only assigned to the CASE statement of the two parameters (IEND unfamed).
In fact, different from the three parameters is that IEND must be equal to the length of the string in the text box. Implementation like this:
Function TextBoxSelect (OTextBox, iStart, IEND) {switch (arguments.length) {copy 1: OTextBox.select (); break; case 2: ip = OTextBox.value.length; / * Falls through by Case3 Continue processing * / Case 3: if (isie) {var orange = OtextBox.createTextRange (); Orange.MoveStart ("Character", iStart; Orange.Movend ("Character", -OTextBox.Value.Length Iend); Orange.Select () } Else if (ismoz) {OTextBox.setSelectionRange (iStart, IEND);}}} In the top of Case 2, we did not use the Break statement, just after executing the statement after the Case 2, then entered the next CASE statement.
Set the text box focus at the last end of the function so that the user knocked into the character can replace the selected text. Function TextBoxSelect (OTextBox, iStart, IEND) {Switch (arguments.length) {casse 1: OtextBox.select (); break; case 2: ip = textbox.value.length; / * falls through * / casse 3: IF ( ISIE) {var Orange = OtExtBox.createTextRange (); Orange.MoveStart ("Character", iStart); Orange.Movend ("Character", -OxtEndBox.value.Length Iend); Orange.Select ();} else (ismoz) {OTextBox.SetSelectionRange (iStart, IEND);}}}}}}}
Ø Replace the text selected in the text box (Translator Note: This feature seems to be not used, readers can jump directly) ---------- another task is to use some other text to replace Currently selected text, for this, create a textBoxReplaceElectr () method, which has two parameters: a text box object that works, and the text to be inserted. Here we want to use the TextRange object, we need to build different code for IE and Mozilla, let us first give IE code: Function TextBoxReplaceSelect (textbox, stext) {if (isie) {var Orange = Document.Selection.createRange (); Orange.collapse (true); orange.select ();} else if (ismoz) {...} OTextBox.focus ();} Online line 4, currently from the document The selection area creates a TextRange object (which can imagine in the text box, trigger by the onkeypress event), and then replace the text in the selection range with a given string, in line 6, call the TextRange object Collapse method, set the width of the selection range to zero; where the Boolean parameter is true, the cursor is biased toward the end of the selection range. Finally, we use the select () method to determine the cursor at the end of the selection range. Use some simple operations of the String object in the Mozilla browser to complete the same effect. We can use the SelectStart and SelectEnd properties of the text box object to determine the start and end points of the selection:
function textboxReplaceSelect (oTextbox, sText) {if (isIE) {var oRange = document.selection.createRange (); oRange.text = sText; oRange.collapse (true); oRange.select ();} else if (isMoz) { var iStart = oTextbox.selectionStart; oTextbox.value = oTextbox.value.substring (0, iStart) sText oTextbox.value.substring (oTextbox.selectionEnd, oTextbox.value.length); oTextbox.setSelectionRange (iStart sText.length iStart Stext.length;} OTextBox.focus ();
On the 9th line above, the selected starting point is saved, and the 10th line looks quite puzzled. String text. The next sentence is to correct the length of the cursor after the location of the text - the start point position plus the length of the text.
Ø Matching --------- Next, you need to handle a method: a given string A, search in a string array and return to the beginning of the first string A String values B (eg, through 'a' in the string array "A" string value "ABCD"). The name of this method is AutoCompleteMatch (), which has two parameters: a number of texts that need to match the text and all text values that are matched.
Direct Search - Repeatedly checks each value in the array. Method Returns a value in the form of TRUE, otherwise it will return NULL if there is no match. All code is as follows:
Function AutoCompleteMatch (Stext, Arrvalues) {for (var i = 0; I It should be noted that: to ensure that this function works correctly, you should sort the strings in the array. Ø Supplement on AutoComplete () Supplement, let's take a look at the automatic completed text box tag (translator Note: ), the autocomplete () method will give three Parameters: Object OtextBox objects for text boxes, Event objects. The calling method is as follows: Considering the Trigger onKeyPress event in the text box (the translator correction: I should use the first button of the character has been entered): function autocomplete (OTextBox, OEvent, Arrvalues) {switch (OEvent.Keycode ) {...}} There are many buttons that need to be masked, such as the cursor key, only need to return True Function AutoComplete (OTEXTBOX, OEVENT, ARRVALUES) {Switch (OEvent.Keycode) {Case 38: // á key Case 40: / / â key case 37: // ß button case 39: // à key case 33: // page down case 36: // home button Case 35: // end key case 13: // entry Case 9: // Tab key case 27: // ESC key case 16: // shift key case 17: // CTRL key case 18: // alt key case 20: // Caps lock key Case 8: // Return button Case 46: // delete key Return True; Break; ...}} Default CASE statement: When the user types a character. In this case statement, you need to complete the following steps: 1. Replace the selected text with the typed character. (Translator Note: This step does not seem to be necessary) 2. Try to get a matching text when typing text. 3. If found, the text is recommended to enter the text that should be entered and selects the matching text that these users do not need to type. This step is the most important thing to determine the characters typed by the user (the keycode property (IE) or Charcode property (Mozilla) of the Event object, and use the string.fromcharcode () method to convert the key code into characters, replace this character Currently selected text, then we need to get the length of text in the text box. Function AutoComplete (OTEXTBOX, OEVENT, ARRVALUES) {switch (OEvent.Keycode) {Case 38: // á key case 40: // â key case 37: // ß key case 39: // à key case 33: // page down key case 36: // home key case 35: // end key case 13: // enter key case 9 : // Tab Key Case 27: // ESC Key Case 16: // SHIFT Key Case 17: // CTRL Key Case 18: // Alt Key Case 20: // Caps Lock Key Case 8: // Retogene Case 46: // delete key Return True; break; default: TextBoxReplaceslect: TEXTBOXREPLACESELECT (ISIE? OEvent.Keycode: OEvent.Charcode); // Translator Note: This step does not seem to be unnecessary, so in the end of the article This line is removed in the sample code. OtextBox.Value.Length; ...}} The following uses autocompleteMatch () method to find a matching value in an array: Function AutoComplete (OTEXTBOX, OEVENT, ARRVALUES) {switch (OEvent.Keycode) {Case 38: // á key Case 40: // â key case 37: // ß key case 39: // à key case 33: // page down key case 36: // home key case 35: // end key case 13: // enter key case 9 : // Tab Key Case 27: // ESC Key Case 16: // SHIFT Key Case 17: // CTRL Key Case 18: // Alt Key Case 20: // Caps Lock Key Case 8: // Retogene Case 46: // Delete key break; default: textboxReplaceSelect (oTextbox, String.fromCharCode (isIE oEvent.keyCode:? oEvent.charCode); var iLen = oTextbox.value.length; var sMatch = autocompleteMatch (oTextbox.value, arrValues); ...}} After the request gets a matching value, we need to make sure if this match is really found. Test the smatch value, if it is not null, you need to replace the text in the text box with SMATCH. Then we use the ILEN (the actual text length typed by the user) as an input parameter of the TextBoxSelect () method to select the text (SMATCH) that has been matched. Function AutoComplete (OTEXTBOX, OEVENT, Arrvalues) {switch (OEvent.Keycode) {Case 38: // Up Arrow Case 40: // Down Arrow Case 37: // LEFT ARROW CASE 39: // Right Arrow Case 33: // Page Up Case 34: // Home Case 35: // End Case 13: // ENTER CASE 9: // Tab Case 27: // ESC Case 16: // Shift Case 17: // ctrl case 18: // alt 20 case: // caps lock case 8: // backspace case 46: // delete return true; break; default:? textboxReplaceSelect (oTextbox, String.fromCharCode (isIE oEvent.keyCode: oEvent.charCode ); var iLen = oTextbox.value.length; var sMatch = autocompleteMatch (oTextbox.value, arrValues);! if (sMatch = null) {oTextbox.value = sMatch; textboxSelect (oTextbox, iLen, oTextbox.value.length); } }} After finishing these events, we must add Return False at the end of the processing method, otherwise, the input character will appear twice. ============================================================================================================================================================================================================= =================== Ø Sample code (for IE browser): Description: This sample code may not perform well in Netscape or Oprea browser, If you have a non-key disk input (mouse copy / paste), it will not be executed.