1. Trang chủ
  2. » Công Nghệ Thông Tin

JavaScript Bible, Gold Edition part 201 docx

10 144 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 90,37 KB

Nội dung

CD-492 Part VI ✦ Appendixes Chapter 25 Examples The following sections contain examples from Chapter 25, “Text-Related Form Objects.” Text Input Object Properties defaultValue NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ ✓ ✓ ✓✓✓✓ Example Important: Listings 25-1, 25-2, and 25-3 feature a form with only one text INPUT ele- ment. The rules of HTML forms say that such a form submits itself if the user presses the Enter key whenever the field has focus. Such a submission to a form whose action is undefined causes the page to reload, thus stopping any scripts that are running at the time. FORM elements for of these example listings contain an onSubmit event handler that both blocks the submission and attempts to trigger the text box onChange event handler to run the demonstration script. In some browsers, such as IE5/Mac, you may have to press the Tab key or click outside of the text box to trigger the onChange event handler after you enter a new value. Listing 25-1 has a simple form with a single field that has a default value set in its tag. A function ( resetField()) restores the contents of the page’s lone field to the value assigned to it in the <INPUT> definition. For a single-field page such as this, defining a TYPE=”reset” button or calling form.reset() works the same way because such buttons reestablish default values of all elements of a form. But if you want to reset only a subset of fields in a form, follow the example button and func- tion in Listing 25-1. Listing 25-1: Resetting a Text Object to Default Value <HTML> <HEAD> <TITLE>Text Object DefaultValue</TITLE> document.formObject.textObject.defaultValue CD-493 Appendix F ✦ Examples from Parts III and IV <SCRIPT LANGUAGE=”JavaScript”> function upperMe(field) { field.value = field.value.toUpperCase() } function resetField(form) { form.converter.value = form.converter.defaultValue } </SCRIPT> </HEAD> <BODY> <FORM onSubmit=”window.focus(); return false”> Enter lowercase letters for conversion to uppercase: <INPUT TYPE=”text” NAME=”converter” VALUE=”sample” onChange=”upperMe(this)”> <INPUT TYPE=”button” VALUE=”Reset Field” onClick=”resetField(this.form)”> </FORM> </BODY> </HTML> form NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ ✓ ✓ ✓✓✓✓ Example The following function fragment receives a reference to a text element as the parameter. The text element reference is needed to decide which branch to follow; then the form is submitted. function setAction(fld) { if (fld.value.indexOf(“@”) != -1) { fld.form.action = “mailto:” + fld.value } else { fld.form.action = “cgi-bin/normal.pl” } fld.form.submit() } Notice how this function doesn’t have to worry about the form reference, because its job is to work with whatever form encloses the text field that triggers this function. document.formObject.textObject.form CD-494 Part VI ✦ Appendixes maxLength NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓✓ Example Use The Evaluator (Chapter 13) to experiment with the maxLength property. The top text field has no default value, but you can temporarily set it to only a few char- acters and see how it affects entering new values: document.forms[0].input.maxLength = 3 Try typing into the field to see the results of the change. To restore the default value, reload the page. name NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ ✓ ✓ ✓✓✓✓ Example Consult Listing 25-2 later in this chapter, where I use the text object’s name, con- vertor , as part of the reference when assigning a value to the field. To extract the name of a text object, you can use the property reference. Therefore, assuming that your script doesn’t know the name of the first object in the first form of a docu- ment, the statement is var objectName = document.forms[0].elements[0].name readOnly NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓✓ document.formObject.textObject.readOnly CD-495 Appendix F ✦ Examples from Parts III and IV Example Use The Evaluator (Chapter 13) to set the bottom text box to be read-only. Begin by typing anything you want in the bottom text box. Then enter the following state- ment into the top text box: document.forms[0].inspector.readOnly = true While existing text in the box is selectable (and therefore can be copied into the clipboard), it cannot be modified or removed. size NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓✓ Example Resize the bottom text box of The Evaluator (Chapter 13) by entering the following statements into the top text box: document.forms[0].inspector.size = 20 document.forms[0].inspector.size = 400 Reload the page to return the size back to normal (or set the value to 80). value NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ ✓ ✓ ✓✓✓✓ Example As a demonstration of how to retrieve and assign values to a text object, Listing 25-2 shows how the action in an onChange event handler is triggered. Enter any lowercase letters into the field and click out of the field. I pass a reference to the entire form object as a parameter to the event handler. The function extracts the value, converts it to uppercase (using one of the JavaScript string object methods), and assigns it back to the same field in that form. document.formObject.textObject.value CD-496 Part VI ✦ Appendixes Listing 25-2: Getting and Setting a Text Object’s Value <HTML> <HEAD> <TITLE>Text Object Value</TITLE> <SCRIPT LANGUAGE=”JavaScript”> function upperMe(form) { inputStr = form.converter.value form.converter.value = inputStr.toUpperCase() } </SCRIPT> </HEAD> <BODY> <FORM onSubmit=”window.focus(); return false”> Enter lowercase letters for conversion to uppercase: <INPUT TYPE=”text” NAME=”converter” VALUE=”sample” onChange=”upperMe(this.form)”> </FORM> </BODY> </HTML> I also show two other ways to accomplish the same task, each one more efficient than the previous example. Both utilize the shortcut object reference to get at the heart of the text object. Listing 25-3 passes the text object — contained in the this reference — to the function handler. Because that text object contains a complete reference to it (out of sight, but there just the same), you can access the value property of that object and assign a string to that object’s value property in a sim- ple assignment statement. Listing 25-3: Passing a Text Object (as this) to the Function <HTML> <HEAD> <TITLE>Text Object Value</TITLE> <SCRIPT LANGUAGE=”JavaScript”> function upperMe(field) { field.value = field.value.toUpperCase() } </SCRIPT> </HEAD> <BODY> <FORM onSubmit=”window.focus(); return false”> Enter lowercase letters for conversion to uppercase: <INPUT TYPE=”text” NAME=”converter” VALUE=”sample” onChange=”upperMe(this)”> </FORM> document.formObject.textObject.value CD-497 Appendix F ✦ Examples from Parts III and IV </BODY> </HTML> Yet another way is to deal with the field values directly in an embedded event handler —instead of calling an external function (which is easier to maintain because all scripts are grouped together in the Head). With the function removed from the document, the event handler attribute of the <INPUT> tag changes to do all the work: <INPUT TYPE=”text” NAME=”converter” VALUE=”sample” onChange=”this.value = this.value.toUpperCase()”> The right-hand side of the assignment expression extracts the current contents of the field and (with the help of the toUpperCase() method of the string object) con- verts the original string to all uppercase letters. The result of this operation is assigned to the value property of the field. The application of the this keyword in the previous examples may be confusing at first, but these examples represent the range of ways in which you can use such ref- erences effectively. Using this by itself as a parameter to an object’s event handler refers only to that single object — a text object in Listing 25-3. If you want to pass along a broader scope of objects that contain the current object, use the this key- word along with the outer object layer that you want. In Listing 25-2, I sent a refer- ence to the entire form along by specifying this.form — meaning the form that contains “this” object, which is being defined in the line of HTML code. At the other end of the scale, you can use similar-looking syntax to specify a partic- ular property of the this object. Thus, in the last example, I zeroed in on just the value property of the current object being defined — this.value. Although the formats of this.form and this.value appear the same, the fact that one is a ref- erence to an object and the other just a value can influence the way your functions work. When you pass a reference to an object, the function can read and modify properties of that object (as well as invoke its functions); but when the parameter passed to a function is just a property value, you cannot modify that value without building a complete reference to the object and its value. Methods blur() NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ ✓ ✓ ✓✓✓✓ document.formObject.textObject.blur() CD-498 Part VI ✦ Appendixes Example The following statement invokes the blur() method on a text box named vanishText: document.forms[0].vanishText.blur() focus() NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ ✓ ✓ ✓✓✓✓ Example See Listing 25-4 for an example of an application of the focus() method in concert with the select() method. select() NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ ✓ ✓ ✓✓✓✓ Example A click of the Verify button in Listing 25-4 performs a validation on the contents of the text box, making sure the entry consists of all numbers. All work is controlled by the checkNumeric() function, which receives a reference to the field needing inspection as a parameter. Because of the way the delayed call to the doSelection() function has to be configured, various parts of what will become a valid reference to the form are extracted from the field’s and form’s properties. If the validation (performed in the isNumber() function) fails, the setSelection() method is invoked after an artificial delay of zero milliseconds. As goofy as this sounds, this method is all that IE needs to recover from the display and closure of the alert dialog box. Because the first parameter of the setTimeout() method must be a string, the example assembles a string invocation of the setSelection() function via string versions of the form and field names. All that the setSelection() function does is focus and select the field whose reference is passed as a parameter. This function is now generalizable to work with multiple text boxes in a more complex form. document.formObject.textObject.select() CD-499 Appendix F ✦ Examples from Parts III and IV Listing 25-4: Selecting a Field <HTML> <HEAD> <TITLE>Text Object Select/Focus</TITLE> <SCRIPT LANGUAGE=”JavaScript”> // general purpose function to see if a suspected numeric input is a number function isNumber(inputStr) { for (var i = 0; i < inputStr.length; i++) { var oneChar = inputStr.charAt(i) if (oneChar < “0” || oneChar > “9”) { alert(“Please make sure entries are integers only.”) return false } } return true } function checkNumeric(fld) { var inputStr = fld.value var fldName = fld.name var formName = fld.form.name if (isNumber(inputStr)) { // statements if true } else { setTimeout(“doSelection(document.” + formName + “. “ + fldName + “)”, 0) } } function doSelection(fld) { fld.focus() fld.select() } </SCRIPT> </HEAD> <BODY> <FORM NAME=”entryForm” onSubmit=”return false”> Enter any positive integer: <INPUT TYPE=”text” NAME=”numeric”><P> <INPUT TYPE=”button” VALUE=”Verify” onClick=”checkNumeric(this.form.numeric)”> </FORM> </BODY> </HTML> document.formObject.textObject.select() CD-500 Part VI ✦ Appendixes Event handlers onBlur onFocus onSelect NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ ✓ ✓ ✓✓✓✓ Example To demonstrate one of these event handlers, Listing 25-5 shows how you may use the window’s statusbar as a prompt message area after a user activates any field of a form. When the user tabs to or clicks on a field, the prompt message associated with that field appears in the statusbar. Listing 25-5: The onFocus event Handler <HTML> <HEAD> <TITLE>Elements Array</TITLE> <SCRIPT LANGUAGE=”JavaScript”> function prompt(msg) { window.status = “Please enter your “ + msg + “.” } </SCRIPT> </HEAD> <BODY> <FORM> Enter your first name:<INPUT TYPE=”text” NAME=”firstName” onFocus=”prompt(‘first name’)”><P> Enter your last name:<INPUT TYPE=”text” NAME=”lastName” onFocus=”prompt(‘last name’)”><P> Enter your address:<INPUT TYPE=”text” NAME=”address” onFocus=”prompt(‘address’)”><P> Enter your city:<INPUT TYPE=”text” NAME=”city” onFocus=”prompt(‘city’)”><P> </FORM> </BODY> </HTML> document.formObject.textObject.onBlur CD-501 Appendix F ✦ Examples from Parts III and IV onChange NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ ✓ ✓ ✓✓✓✓ Example Whenever a user makes a change to the text in a field in Listing 25-6 and then either tabs or clicks out of the field, the change event is sent to that field, triggering the onChange event handler. Because the form in Listing 25-6 has only one field, the example demonstrates a technique you can use that prevents a form from being “submitted” if the user acci- dentally presses the Enter key. The technique is as simple as defeating the submis- sion via the onSubmit event handler of the form. At the same time, the onSubmit event handler invokes the checkIt() function, so that pressing the Enter key (as well as pressing Tab or clicking outside the field) triggers the function. Listing 25-6: Data Validation via an onChange event Handler <HTML> <HEAD> <TITLE>Text Object Select/Focus</TITLE> <SCRIPT LANGUAGE=”JavaScript”> // general purpose function to see if a suspected numeric input is a number function isNumber(inputStr) { for (var i = 0; i < inputStr.length; i++) { var oneChar = inputStr.substring(i, i + 1) if (oneChar < “0” || oneChar > “9”) { alert(“Please make sure entries are numbers only.”) return false } } return true } function checkIt(form) { inputStr = form.numeric.value if (isNumber(inputStr)) { // statements if true } else { form.numeric.focus() form.numeric.select() Continued document.formObject.textObject.onChange . DefaultValue</TITLE> document.formObject.textObject.defaultValue CD-493 Appendix F ✦ Examples from Parts III and IV <SCRIPT LANGUAGE= JavaScript > function upperMe(field) { field.value = field.value.toUpperCase() } function. to uppercase (using one of the JavaScript string object methods), and assigns it back to the same field in that form. document.formObject.textObject.value CD-496 Part VI ✦ Appendixes Listing 25-2:. form. document.formObject.textObject.select() CD-499 Appendix F ✦ Examples from Parts III and IV Listing 25-4: Selecting a Field <HTML> <HEAD> <TITLE>Text Object Select/Focus</TITLE> <SCRIPT LANGUAGE= JavaScript > // general

Ngày đăng: 06/07/2014, 06:20