W hen yo ur page needs input from visito rs beyond
“yes” o r “ no” answers, text fields are the interface
elements tha t provide the blank spaces. W hether you specify the one-line INPUT element o r the m ulti-line TEXTAREA ele
ment, this is where visitors can not only express themselves, but also enter inform ation in formats that m ight cause your carefully constructed back-end database to go haywire. More often than not, it is the text box that benefits most from client- side form validation.
Despite the fact th a t the prim a ry user action in a text box is typing, keyboard events became available to scripters only starting w ith the version 4 browsers from both M icrosoft and Netscape. But they arrived fu lly formed, w ith a suite of events for the downstroke, upstroke, and complete press-and-release action of typing a character. From there, the event object takes over to help scripts uncover the character code and whether the user held down any m odifier keys while typing the character. You can find examples of this kind of event han
dling in the examples for Chapters 1 and 13 of this book.
Text boxes are not always as scriptable as you m ight like them to be. Modern browsers can apply style sheets to adjust font characteristics of the complete text box, but you cannot, say, set some of the words inside a text box to bold. Even something as common (in other programs) as having the text insertion pointer autom atically plant itself at the end of exist
ing text is possible so far only in IE4+/Windows via the TEXTAREA’s cr eateTextRangei ) method and associated TextRange object methods (see TextRange object examples in Chapter 5 of this book). The moral of the s to ry is to keep yo ur expectations for the powers of text fields at moderate levels.
♦ ♦ ♦ ♦
In This C ha p te r Capturing and modifying text field contents
Triggering action and entering text
Giving focus to a text field and selecting its contents
♦ ♦ ♦ ♦
3 5 8 JavaScript Examples Bible: The Essential Companion to JavaScript Bible
Examples Highlights
♦ Because the value property holds the string value of the text box, it is also the p ro pe rty you use to dump new text into a box. Listings 25-2 and 25-3 read from and w rite to a text box, transform ing the entered contents along the way.
You see three different approaches to the task.
♦ During client-side validation, you help the v is ito r by directing the text inser
tio n pointer to the text field tha t failed a validation. Listing 25-4 shows how to use the focus ( ) and sel ect ( ) methods along w ith a workaround for an IE/Windows tim ing problem that norm ally gets in the way.
♦ Use the onChange event handler (not onBl ur) as a trigger for real-time data validation, as dem onstrated in Listing 25-6. You also see the syntax tha t pre
vents form submission when validation fails.
♦ In IE4+ and NN6, you can adjust the size of a TEXTAREA element after the page has loaded. The example for the col s and rows properties lets you see the results in The Evaluator.
Text Input Object
Properties
defaultValue
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
C om pa tib ility / / / / / / / / /
Example
Im portant: Listings 25-1, 25-2, and 25-3 feature a form w ith only one text INPUT element. 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 onSubmi t event handler that both blocks the submission and attempts to trigger the text box onChange event handler to run the dem onstration 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 w ith a single field that has a default value set in its tag. A function ( r e s e t Fi el dO ) restores the contents of the page’s lone field to the value assigned to it in the < I N PUT> definition. For a single-field page such as this, defining a TYPE=" reset" button o r calling form, r es et( ) works the same way because such buttons reestablish default values of all elements of a form. But if you
document JormObject.textObject.defauitValue
Chapter 9 ♦ Text-Related Form Objects (Chapter 25) 3 5 9
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>
<SCRIPT LANGUAGE“ "JavaScript'^
function upperMe(field) {
field.value = field.value.toUpperCase() )
function resetField(form) {
form.converter.value = form.converter.defaultValue }
</SCRIPT>
</HEAD>
<B0DY>
<F0RM onSubmit=”window.focus(); return false">
Enter lowercase letters for corversion to uppercase: < INPUT TYPE="text”
NAME="converter” VALUE="sample” onChange="upperMe(this)">
< INPUT TYPE="button" VALUE="Reset Field"
onClick="resetFiel d (t h i s .form)">
</F0RM>
</B0DY>
</HTML>
f o r m
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
C om pa tib ility ✓ ✓ ✓ ✓ / / / / /
Example
The follow ing function fragment receives a reference to a text element as the parameter. The text element reference is needed to decide w hich branch to follow;
then the form is subm itted.
function setAction(fld) {
if (fid.value.indexOf("@") !- -1) I
fid.form.action = "mailto:" + fid.value ) else {
fid.form.action = "cgi-bin/normal.pi”
)
fid.form.submitt)
document.formObject.textObject.toim
3 6 0 JavaScript Examples Bible: The Essential Companion to JavaScript Bible
Notice how this function doesn’t have to w o rry about the form reference, because its job is to w o rk w ith whatever form encloses the text field tha t triggers this function.
maxLength
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
C om pa tib ility / / / /
Example
Use The Evaluator (Chapter 13 in JavaScript Bible) to experim ent w ith the m a x L e n g t h property. The top text field has no default value, but you can tem porar
ily set it to only a few characters and see how it affects entering new values:
d o c u m e n t .f o r m s [ 0 ] .input.maxLength = 3
T ry typing in to 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
C om pa tib ility / / / / / / / / /
Example
Consult Listing 25-2 later in this chapter, where I use the text object’s name, con - vertor, as p art of the reference when assigning a value to the field. To extract the name of a text object, you can use the p ro pe rty reference. Therefore, assuming tha t y o u r scrip t doesn’t know the name of the firs t object in the firs t 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
C om pa tib ility / / / /
Example
Use The Evaluator (Chapter 13 in JavaScript Bible) to set the bottom text box to be read-only. Begin by typing anything you want in the bottom text box. Then enter the follow ing statement into the top text box:
document JormObject.textObject.readOniY
Chapter 9 ♦ Text-Related Form objects (Chapter 25) 3 6 1
document.forms[0].inspector.readonly = true
W hile existing text in the box is selectable (and therefore can be copied into the clipboard), it cannot be modified o r removed.
si ze
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
C om pa tib ility / / / /
Example
Resize the bottom te xt box of The Evaluator (Chapter 13 in JavaScript Bible) by entering the follow ing statements into the top text box:
document.forms[0].inspector.size = 20 document.forms[0].inspector.Si2e = 400
Reload the page to return the size back to normal (o r set the value to 80).
val ue
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
C om pa tib ility / / / / / / / / /
Example
As a dem onstration of how to retrieve and assign values to a text object, Listing
25-2 shows how the action in an o n C h a n g e 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.
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 = inpitStr.toUpperCaseO 1
</SC RIPT>
</HEAD>
Continued
áocument.formObject.textObject.value
3 6 2 JavaScript Examples Bible: The Essential Companion to JavaScript Bible
Listing 25-2 (continued)
<B0DY>
<F0RM onSubmit="window.focus(); return false”>
Enter lowercase letters for corversion to uppercase: < INPUT TYPE="text'' NAME="converter" VALUE="sample” onChange="upperMe(this.form)">
</F0RM>
</B0DY>
</HTML>
I also show tw o other ways to accom plish the same task, each one more efficient than the previous example. Both utilize the sh ortcu t object reference to get at the heart of the text object. Listing 25-3 passes the text object — contained in the t h i s reference— to the function handler. Because tha t text object contains a complete reference to it (out of sight, but there ju s t the same), you can access the value p ro p e rty of th a t object and assign a string to tha t object’s val ue p roperty 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.toUpperCasei) )
</SC RIPT>
</HEAD>
<B0DY>
<F0RM onSubmit=''window.focus(); return false">
Enter lowercase letters for corversion to uppercase: < INPUT TYPE="text”
NAME="converter" VALUE=nsample” onChange="upperMe(this)">
</F0RM>
</B0DY>
</HTML>
Yet another way is to deal w ith the field values d ire ctly in an embedded event han d le r— instead of calling an external function (w hich is easier to maintain because all scripts are grouped together in the Head). W ith the function removed from the document, the event handler a ttribu te of the <1 NPUT> tag changes to do all the work:
< INPUT TYPE="text” NAME="converter" VALUE="sample"
onChange="this.value = this.value.toUpperCase()">
document JormObject.textObject.value
Chapter 9 ♦ Text-Related Form Objects (Chapter 25) 3 6 3
The right-hand side of the assignment expression extracts the current contents of the field and (w ith the help of the t o U p p e r C a s e O method of the string object) converts the original string to all uppercase letters. The result of this operation is assigned to the value p ro p e rty 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 w hich you can use such references effectively. Using this by itself as a parameter to an object’s event han
dler 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 t h i s keyword along w ith the outer object layer tha t you want. In Listing 25-2,1 sent a ref
erence to the entire form along by specifying thi s . f o r m— meaning the form that contains “th is ” object, w hich is being defined in the line of HTML code.
A t the other end of the scale, you can use sim ilar-looking syntax to specify a par
ticu la r p ro p e rty of the t h i s object. Thus, in the last example, I zeroed in on ju st the val Lie p ro pe rty of the current object being defined — thi s . val ue. Although the form ats of thi s . f orm and t h i s . val ue appear the same, the fact that one is a ref
erence to an object and the other ju st a value can influence the way your functions work. When you pass a reference to an object, the function can read and m odify properties of th a t object (as well as invoke its functions); but when the parameter passed to a function is ju st a p roperty value, you cannot m odify that value w ith o u t building a complete reference to the object and its value.
Methods
b l u r ()
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
C om pa tib ility ✓ ✓ ✓ / / / / / /
Example
The follow ing statement invokes the bl ur ( ) method on a text box named vani shText:
document.forms[0].vanishText.blur()
f o c u s ( )
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
C om pa tib ility / / / / / / / / /
Example
See Listing 25-4 for an example of an application of the f ocus ( ) method in con
ce rt w ith the sel ect ( ) method.
document.formObject.textObject.focusQ
3 6 4 JavaScript Examples Bible: The Essential Companion to JavaScript Bible
s e l e c t ()
NN2 NN3 NN4 NN6 IE 3/J1 IE3/J2 IE4 IE5 1E5.5
Compatibility y y y y y y y y y
Example
A click of the Verify button in Listing 25-4 perform s a validation on the contents of the text box, making sure the e n try consists of all numbers. A ll w ork is controlled by the checkNumeri c ( ) function, w hich receives a reference to the field needing inspection as a parameter. Because of the way the delayed call to the doSel e c t i on () function has to be configured, various parts of w hat w ill become a valid reference to the form are extracted from the fie ld ’s and fo rm ’s properties. If the validation (perform ed in the i sNumber () function) fails, the setSel e c t i o n ( ) method is invoked after an a rtific ia l delay of zero milliseconds. As goofy as this sounds, this method is all tha t IE needs to recover from the display and closure of the alert dia
log box. Because the firs t parameter of the s e t T i meout ( ) m ethod must be a string, the example assembles a string invocation of the s e t S e l e c t i o n ( ) function via string versions of the form and field names. A ll that the setSel e c t i on ( ) function does is focus and select the field whose reference is passed as a parameter. This function is now generalizable to w ork w ith m ultiple te xt boxes in a more complex form.
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" || oreChar > "9") {
alert("Please make sure entries are integers only.") return false
) )
return true )
function checkNumeric(fld) { var inputStr = fid.value var fldName = fid.name var formName = fid.form.name if (isNumber(inputStr)) {
// statements if true ) else (
documentJormObject.textObject.se\ectQ
Chapter 9 ♦ Text-Related Form Objects (Chapter 25) 3 6 5
setTimeout("doSe lec ti on (d oc um en t." + formName + " + fldName + 0)
} )
function doSelection(fld) ( fld.focus()
fld.selectO )
</SCRIPT>
</HEAD>
<B0DY>
<F0RM NAME="entryForm" onSubmit="return false">
Enter any positive integer: < INPUT TYPE="text" NAHE="numeric,,X P >
< INPUT TYPE="button" VALUE="Verify" onClick="checkNumeric(this.form.numeric)”>
</F0RM>
</BUUY>
</HTML>
Event handlers
onBlur onFocus onSelect
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
C om pa tib ility / / / / / / / / /
Example
To demonstrate one of these event handlers, Listing 25-5 shows how you may use the w indow ’s statusbar as a prom pt message area after a user activates any field of a form. When the user tabs to o r clicks on a field, the prom pt message asso
ciated w ith tha t field appears in the statusbar. In Figure 9-1, the user has tabbed to the second text box, w hich caused the statusbar message to display a prom pt for the field.
Listing 25-5: The onFocus event Handler
<HTML>
<HEAD>
<TITLE>E1ements Array</TITLE>
<SCRIPT LANGUAGE“ "JavaScript">
Continued
document.formObject.textObject.onBlui
3 6 6 JavaScript Examples Bible: The Essential Companion to JavaScript Bible
Listing 25-5 (continued)
function prompt(msg) {
window.status = "Please enter your " + msg + "."
}
</SCRIPT>
</HEAD>
<B0DY>
<F0RM>
Enter your first name:<INPUT TYPE="text" NAME="firstName"
onFocus=”prompt('first name' )"><P>
Enter your last name:<INPUT TYFE="text" NAME="1astName"
onFocus="prompt('last name')”><P>
Enter your address:<INPUT TYPE="textr NAME="address"
onFocus="prompt('address')"><P>
Enter your city:<INPUT TYPE=''text" NAME="city" onFocus=''prompt('city')"><P>
</F0RM>
</BODY >
</HTML>
3 E le m e n ts A r r a y - M ic ro s o ft In te r n e t E x p lo re r H S Q I
File Edit V ie w F avorites Tools Help □
£ 0 (2 a Jü J
Forward Slop Refresh Home Search Favorites History Mail
J
Enter your first nam e:|Huckleberiy Enter your last n a m e j Enter your address]
Enter your cityl
zl
Please e n te r yo u r last n a m e .[^ "JMy C om puter
Figure 9-1 : An onFocus event handler triggers a statusbar display.
document JormObject.textObject.onBlur
Chapter 9 ♦ Text-Related Form Objects (Chapter 25)
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 o r clicks out of the field, the change event is sent to tha t 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 tha t prevents a form from being “subm itted” if the user acci
dentally presses the Enter key. The technique is as simple as defeating the submis
sion via the onSubmi t event handler of the form. A t the same time, the onSubmi t event handler invokes the c h e c k 11 ( ) function, so tha t pressing the Enter key (as w ell as pressing Tab o r 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 = i nput.Str .suhst.ri ng(i, i + 1) if (oneChar < "0" || oreChar > "9") {
alert("Please make sure entries are numbers only.") return false
) )
return true )
function checklt(form) (
inputStr = form.numeric.value if (isNumber(inputStr)) {
// statements if true } else {
form.numeric.focus() form.numeric.select() )
)
</SC RIPT>
</HEAD>
<B0DY onSubmit="checkIt(this); return false">
Continued
3 6 7
document.formObject.textObject.onChange
3 6 8 JavaScript Examples Bible: The Essential Companion to JavaScript Bible
Listing 25-6 (continued)
< F 0 R M >
E n ter any p o s i t i v e integer: <INPUT T Y P E = " t e x t " NAME o n C h a n g e = " c h e c k I t ( t h i s . f o r m ) " X P >
< / F 0 R M >
< / B 0 D Y >
< / H T M L >
= " n u m e r i c"
TEXTAREA Element object
Properties
col s rows
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓ / / /
Example
Use The Evaluator to play w ith the c o l s and r o w s p ro p e rty settings for the Results textarea on tha t page. Shrink the w id th of the textarea by entering the fol
low ing statement into the top text box:
d o c u m e n t . f o r m s [ 0 ] . o u t p u t . c o l s = 30
And make the textarea one row deeper:
d o c u m e n t .f o r m s [ 0 ] . o u t p u t .ro ws++
Methods
createTextRangeC )
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility / / /
Example
See the example fo r the T e x t R a n g e , mo v e () method in Chapter 5 of this book to see how to control the te xt insertion pointer inside a TEXTAREA element.
♦ ♦ ♦
TEXTAREA.createTextRange 0