Coolnerds Electronic JavaScript Reference

Note: The links below won't work until the entire document has been downloaded. And that may take up to a minute, depending on the speed of your modem.

If you like, you can download a zipped version of the Coolnerds JavaScript Reference to your own PC. After downloading javaref.zip to your PC, and unzipping it, you can open javaref.htm on your PC to use your local copy of the reference.

about escape() function options array
warnings eval() function parseFloat() function
//, <!… comments Event Handlers parseInt() function
\char characters for statement password object
+, *, ...operators for…in statement radio object
anchor object form object Reserved Words
anchors array frame object reset object
arithmetic operators function statement return statement
assignment operators hidden object select object
bitwise operators history object string object
break statement if statement string operators
Button object isNAN() function submit object
Checkbox object link object text object
color values links array textarea object
comments location object this keyword
comparison operators logical operators unescape() function
conditional operator Math object var statement
continue statement Navigator object while statement
Date object new keyword window object
document object operator precedence with statement
elements array operators



Top


+ - * / ? % ++ -- && || etc. operators

Operators "operate" on values. You deal with operators every day in your regular life - you probably just never heard them called that. For example, everyone knows that 1+1=2. In that statement, the + sign is the operator. JavaScript offers many operators beyond the basic ones used in arithmetic.

Syntax

Though specific rules of syntax vary with some operators, the typical syntax is

variable = value operator value

where variable is the name of a variable used to store a value, value is a number, string, value, expression, or property of an object, and operator is one of the operators described here.

Description

The sections that follow group JavaScript into classes based on the type of operation performed.

Arithmetic operators

Arithmetic operators act on numbers. Table 1 lists the arithmetic operators offered in JavaScript and provides examples of each.

Table 1: JavaScript's Arithmetic Operators.

Operator Used For Example Equals
+ Addition 1+2 3
- Subtraction 12-10 2
* Multiplication 2*3 6
/ Division 10/3 3.3333333333
% Modulus 10%3 1
++ Increment x=5
x++
x=6
-- Decrement x=5
x--
x=4
- Unary negation -20 negative 20

The modulus of a number is the remainder after the first division. For example, 10/3 results in 3, remainder 1. The modulo (%) operator returns that remainder, 1.

The increment operator, ++, is just a shortcut way of saying variable + 1. For example, the two statements that follow mean exactly the same thing. The latter one is just shorter and quicker to type: x = x + 1 x++

The same holds true for the decrement (--) operator.

With the negation operator, if the minus sign is used in front of a value without being part of a larger expression, then JavaScript assumes it indicates a negative number, just as in day-to-day arithmetic. For example x= 5 y= -x results in x being equal to 5 and y being equal to -5.

Top


Assignment operators

To assign a value to a variable, use the simple = operator with the syntax

variablename = value

For example x=15 y=20 z=x+y

After all three lines have been executed, the variable x contains the number 15, the variable y contains 20, and the variable z contains 35 (the sum of 15+20).

Some shorthand operators exist that you can use to do some arithmetic and assign the result to a value in one fell swoop. Those operators are shown in Table 2.

Table 2: JavaScript's Assignment Operators.

Operator Example Means
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
% x%=y x=x%y

Top


Comparison and logical operators

Comparison and logical operators compare two values and return either true or false. Table 3 lists the comparison operators. Table 4 displays the logical operators:

Table 3: JavaScript's Comparison Operators.

Operator Meaning Example
== is equal to 10==3 is false
!= does not equal 10!=3 is true
> is greater than 10>3 is true
>= is greater than or equal to 10>=3 is true
< is less than 10<3 is false
<= is less than or equal to 10<=3 is false

Table 4: JavaScript's Logical Operators.

Operator Meaning If x=10 and y= 5 then…y
&& AND (x = 10) && (y < 10) is true
|| OR (x=10) || (y=10) is true
! NOT x !=y is true

Top


String operators

A string is a chunk of text, such as hello, rather than a number such as 10. Unlike numbers, you cannot add, subtract, multiply, and divide strings. Example: 2*3 = 6 is fine. But what is "Hello" * "There"? The question makes no sense.

You can, however, concatenate strings, which is a fancy name for "stick them together." You use the + operator to concatenate strings. Here is an example where we create three variable, x, y, and z, all of which contains strings:

x="Hello"

y="There"

z=x+y

The result is that z now contains HelloThere.

Why is there no space between the words? Because to a computer, strings are just meaningless strings of characters. To a computer, the string hello in no more meaningful than the string ghfkredg. They are both just strings. If you want to add a space between the words, you can pop a space into the expression. A literal space would be a space enclosed in quotation marks (" "). Hence, this series of commands x="Hello" y="There"

z=x+" "+y

results in z containing Hello There. A shortcut operator also exists for string concatenation +=. For example x="Hello" y="There"

x+=" "+y

in which case x equals itself with a space and y tacked on. Ergo, x then contains Hello There.

Top


Conditional operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. The operators for a conditional expression are ? and : using this syntax:

myvar = (condition) ? value1 : value2

For example, the conditional expression that follows is a shorthand way of saying "If the variable named gender contains F, then put the string 'Ms.' in the variable named salutation. If the variable named gender does not contain F, then put the string 'Mr.' into the variable named salutation":

salutation = (gender=="F") ? "Ms." : "Mr."

Top


Bitwise operators

Bitwise operators treat their values as binary numbers (1s and 0s) rather than as numeric values. You may never need to use these. I never have. I also have yet to see a JavaScript program that uses them. If I were you, I wouldn't waste any brain cell energy trying to memorize them. But just in case you do come across a bitwise operator, Table 5 shows what each one does.

Table 5: JavaScript's Bitwise Operators.

Operator Action Example
& bitwise AND 10&3=2
| bitwise OR 10|3=11
^ bitwise exclusive OR 10^3=9
<< left shift 10<<3=80
>> Sign-propagating right shift 10>>3=1
>>> Zero-fill right shift 10>>>3=1

Some shortcut operators also exist for bitwise assignments, as listed in Table 6.

Table 6: JavaScript's Bitwise Assignment Operators.

Operator Example Means
<<= x<<=y x=x<<y
>>= x>>=y x=x>>y
>>>= x>>>=y x=x>>>y
&= x&=y x=x&y
^= x^=y x=x^y
|= x|=y x=x|y


Top


Operator precedence

JavaScript operators follow the standard order of precedence. But you can override natural precedence with parentheses. For example

5+3*10

equals 35 because the multiplication is naturally carried out first (according to the rules of precedence). That is, the machine first evaluates 10*3, which equals 30, and then adds 5 to that to get 35.

This expression has a different result:

(5+3)*10

This expression results in 80 because the parentheses force the addition to be carried out first (5+3 equals 8). That result then is multiplied by 10 to result in 80. Table 7 shows the order of precedence of the operators, from highest to lowest, when you do not use parentheses in an expression. Operators at the same level of precedence within an expression are carried out in left-to-right order.

Table 7: JavaScript Operators Order of Precedence.

Action Operator(s)
call, member (),[]
negation/increment ! ~- ++ --
multiply/divide * / %
addition/subtraction + -
bitwise shift << >> >>>
comparison < <= > >=
equality == !=
bitwiseAND &
bitwise XOR ^
bitwise OR |
logical AND &&
logical OR ||
conditional ?:
assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
comma ,

Top


//, /*, */, <! -- and //--> comments

These comments identify commands within JavaScript code. To use them, you must place them between the <SCRIPT> ... </SCRIPT> tags.

Syntax

This comment

// comment

is a single-line comment where comment is any one line of text, whereas

/* comment */

is a multiple-line where comment is any amount of plain-English text.

<!-- comment

code

// comment -->

This preceding example shows the hide comment, where comment is any (optional) text and code is JavaScript instructions. This comment hides JavaScript code from non-JavaScript browsers.

Example

<SCRIPT Language = "JavaScript">
<!-- This will start hiding code from non-JavaScript browsers.

//This is a comment, and will be ignored.
document.write ("Hello World")

/*Here's a two line comment that will 
be ignored */
document.write ("Goodbye World")

// and this stops the hiding -->
</SCRIPT> 







Top


\b \f \n \r \t \" special characters

Special characters used to cause a string to perform some action when printed.

Syntax

The syntax for special characters is

variable = "text \specialcharacter text"

or

document.write ("text \specialcharacter text")

where variable is the name of a variable that stores the string, text is any text, and specialcharacter is b, f, n, r, t, or a quotation mark.

Description

The special characters and the role played by each are listed in Table 8. However, be forewarned that only the \" character appears to work in Windows browsers.

Table 8: JavaScript Special Characters for String Literals.

Character Meaning
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t tab
\" quotation mark

Example

myQuote = "Mary said \"Hello Joe\" as she rode by."
document.write(myQuote) 






When executed, the document.write statement puts this on the screen:

Mary said "Hello Joe" as she rode by.

Top


anchor object (anchors array)

This is a built-in array that contains one element for every anchor in the current Web page.

Syntax

The syntax for the anchor object is

document.anchor[n]

where n is some number representing an item's position in the list. Alternatively, you can use

document.anchor.length

to identify the number of items in the list.

Properties

.length identifies how many items are in the anchors array.

Description

When your page is displayed to a reader, the anchors array creates an element for each anchor in the page. The first anchor is anchor[0], the next is anchor[1], and so forth. The anchors.length value reflects the number of items in the array.

The actual name of the anchor is always null. That is, you cannot use the anchors array to discover an anchor's name. You also cannot create an anchor programatically. For example, the statement anchor[0]="howdy" does nothing.

The anchor object is a property of the larger document object.

Example

The custom function in the following listing returns true if the current page has at least one anchor in it. It returns false if the page contains no anchors.

function hasAnchors() {
     retval = true 
     if (document.anchors.length == 0) {
          retval = false 
     } return retval 
}







Top


break statement

This statement immediately terminates an ongoing for or while loop.

Syntax

The syntax for the break statement is

break

Description

The break statement can be used only within the curly braces following a for or while loop. When executed, break terminates the loop and passes execution to the first statement after the loop's closing curly brace (}).

Example

The custom contains() function that follows looks at each character in a string (lstring). If it finds a character that matches the character stored in onechar, it sets the variable retval to true and stops looking.

function contains(onechar,lstring) {
     retval = false
     for (var i=1;i<=lstring.length;i++) {
          if (lstring.substring(i,i+1)==onechar) {
               retval=true break 
          } 
     } 
     return retval
}









Top


Button object

This object refers to a clickable button on a form.

Syntax

The syntax for the button object is

<INPUT type="button" value="button text">

where button text is the text that appears on the button face. The <INPUT...> tag must be placed within a pair of <FORM>...</FORM> tags. The INPUT tag can also contain other INPUT attributes, including JavaScript event handlers.

Properties

.name reflects the NAME attribute in the <INPUT> tag

.value reflects the VALUE attribute in the <INPUT> tag

Methods

.click() Clicks the button

Event handlers

onClick Triggered when the reader clicks the button.

Description

Use button and the onClick event handler in the <INPUT> tag of a form - not in JavaScript code. The <SCRIPT>...</SCRIPT> tags are not required but the <FORM>...</FORM> tags are.

The button object is a property of the larger form object.

Example

The following example displays on a button on the reader's Web page that says Click Me on its face. When the reader clicks the button, an alert message says Howdy!

<FORM name="OneButt">
<INPUT type="button" value="Click Me" onClick = "alert('Howdy!')">
</FORM>









Top


Checkbox object

In an <INPUT> tag, this object specifies a checkbox form field. In JavaScript, it refers to a checkbox on a form.

Syntax

The following line

<INPUT type="checkbox">

when placed between a pair of <FORM> tags, puts a checkbox on the current form. The statement also can contain other INPUT attributes, including the CHECKED, NAME, and VALUE attributes, and a JavaScript onClick event handler.

Properties

.checked true if box is checked, false if box is clear

.defaultchecked Reflects the CHECKED attribute of the <INPUT> tag

.name Reflects the NAME attribute of the <INPUT> tag

.value Reflects the VALUE attribute of the <INPUT> tag

Methods

.click() Programatically clicks on the checkbox.

Event handlers

onClick Triggered when the reader clicks on the checkbox

Description

To create a checkbox in Word IA, choose Insert > Form Field > Check box.) To create a checkbox manually, use the TYPE="checkbox" attribute in an <INPUT> tag between a pair of <FORM>...</FORM> tags.

Use event handlers within the <INPUT> tag to trigger a script when the reader clicks on the checkbox.

Example

In the following example, the areyasure() custom function displays a custom alert message. However, that function is called up only if the reader opts to pay now by credit card when presented with the form. Note the <INPUT ... TYPE="checkbox"> tag and its onClick property that calls up areyasure only if the checkbox is checked.

<HEAD>
<SCRIPT Language = "JavaScript">
     function areyasure() {
     alert("Think twice. This is not a secure web site!")
}
</SCRIPT>
</HEAD> 

<BODY>
<FORM NAME="payment_method">
     <INPUT TYPE="checkbox" NAME="creditcard" onClick="if (this.checked) {areyasure()}">
     Pay now by credit card
</FORM>
<BODY> 






Here's another example where a custom function named clearCheckbox() automatically removes the checkmark from a checkbox by settings its .checked property to false. The function is called when the reader clicks the button defined by the <INPUT type='button'> tag:

<HTML>
<HEAD>
<SCRIPT Language = "JavaScript"> 
function clearCheckbox() {
     if (document.cake.eat.checked) {
          document.cake.eat.checked = false
          alert ("Can't have cake and eat it too") 
     }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="cake">
     <INPUT type="checkbox" name="eat"> I want to eat my cake.<P>
     <INPUT type='button' value = 'I want to keep my cake' onClick = 'clearCheckbox()'> 
</FORM>
</BODY>
</HTML> 






Try it

Top


Color values

You can click here to see the color names and triplets.

Description

You can change the background color of a document at any time by setting document.bgColor to a new color. However, you cannot change any foreground colors - fgColor (TEXT), alinkcolor, and so on - if the page has already been written and is displayed on the screen. To change foreground colors, you need to close the input stream to the document (document.close()), open a new document (document.open(), and rewrite the entire page with new color values in the <BODY> tag of the page.

Example

This little page shows a button that, when clicked, changes the background color of the current page from pink to purple or vice versa. Note that the JavaScript if() statement still requires the triplet with a pound sign - '#ffc0cb' rather than 'pink'.

<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function reversecolor() { 
     // The if statement still requires the triplet. 
     if (document.bgColor == '#ffc0cb') { 
          document.bgColor = 'purple'}
     else {
          document.bgColor = 'pink'
     }
}
</SCRIPT>
<BODY bgColor = 'pink'>
<FORM>
     <INPUT type = "button" value="click me" onclick="reversecolor()">
</FORM> 
</BODY>
</HTML> 






Try it

See also the Color Schemer page (alancolr.htm) which presents an example that lets you select both a background and foreground (TEXT) color.

Top


continue statement

This statement terminates the remaining statements in a for or while loop and continues execution at the top of the loop (the next iteration of the loop).

Syntax

The syntax for this statement is

continue

Description

The continue statement makes sense only within the curly braces of a for or while loop. Unlike the break statement, continue passes control back to the top of the loop. It does not terminate the loop. In a for loop, continue jumps back to and executes the increment-expression. In a while loop, continue jumps back to and evaluates the condition statement.

Example

Opening the following page

<HTML>
<BODY>
<SCRIPT Language = "JavaScript">
i=0
while (i < 10) {
     i++
     if (i/3 == parseInt(i/3)){
          continue
     }
     document.write ("i=",i,"<BR>")
}
</SCRIPT>
</BODY> 








displays this on the Web browser screen.

i=1

i=2

i=4

i=5

i=7

i=8

i=10

Try it

Numbers that are evenly divisible by three (3, 6, 9) are omitted because the if() statement in the while loop forces the loop to start over, without getting to the document.write() statement, when the value of i is evenly divisible by 3.

Top


Date object

This object defines a date/time as the number of milliseconds since January 1, 1970.

Syntax

To create a new date object, use the following syntax:

dateObjectName = new Date()

or

dateObjectName = new Date(year, month, day)

or

dateObjectName = new Date(year, month, day, hours, minutes, seconds)

or

dateObjectName = new Date("month day, year hours:minutes:seconds")

where dateObjectName is either the name of a new object or a property of an existing object, month, day, year, hours, minutes, and seconds are integers or, in the last form, strings.

To use Date methods, follow this syntax

dateObjectName.methodName(parameters)

where dateObjectName is either the name of an existing Date object or a property of an existing object and methodName is one of the methods listed in the following section.

Methods

.getDate() Returns the day of month (1 to 31)

.getDay() Returns the day of the week from 0 (Sunday) to 6 (Saturday)

.getHours() Returns the hour from 0 (midnight) to 23 (11:00 PM)

.getMinutes() Returns the minute from 0 to 59

.getMonth() Returns the month from 0 (January) to 11 (December)

.getSeconds() Returns the seconds (0 to 59)

.getTime() Returns the milliseconds transpired since 1/1/70

.getTimezoneOffset() Returns the difference between local time and GMT (meridian time)

.getYear() Returns the two-digit year, such as 97 for 1997

.parse(string) Converts a string in Dec 25, 1997 to the number of milliseconds transpired since 1/1/70

.setDate(num) Sets the day of an existing object to num where num is a value between 1 and 31

.setHours(num) Sets the hour of an existing object to num where num is a value between 0 and 23

.setMinutes(num) Sets the minutes of an existing object to num where num is a value between 0 and 59

.setMonth(num) Sets the month of an existing object to num where num is a value between 0 and 11

.setSeconds(num) Sets the seconds of an existing object to num where num is a value between 0 and 59

.setTime(num) Sets the date and time of an existing object to num where num represents the number of milliseconds transpired from 1/1/70

.setYear(num) Sets the year of an existing object to num where num is a value between 70 and 99

.toGMTString(dateobject) Converts the dateobject to a string expressed in Internet GMT format

.toLocaleString(dateobject) Converts the dateobject to a string expressed in local date/time format

.UTC(year, month, day [, hrs] [, min] [, sec]) Converts date/time values expressed in Universal Coordinated Time values to the number of milliseconds transpired since 1/1/70

Description

The way JavaScript handles dates is very similar to the way Java handles dates. Both languages store dates internally as the number of milliseconds that have elapsed since January 1, 1970 00:00:00. Dates prior to 1970 are not allowed.

Example

Opening the following page on March 31, 1997, at approximately 4:30 pm

<HTML>
<BODY>
<SCRIPT Language="JavaScript"> 
today = new Date()
document.write ('today = ',today,'<br>')
document.write ('today.getDate() = ',today.getDate(),'<br>')
document.write ('today.getHours() = ',today.getHours(),'<br>')
document.write ('today.toGMTString() = ',today.toGMTString(),'<br>')
document.write ('today.toLocaleString() = ',today.toLocaleString())
</SCRIPT>

</BODY>
</HTML> 






would display this in the Web browser document:

today = Mon Mar 31 16:30:01 PST 1997
today.getDate() = 31
today.getHours() = 16
today.toGMTString() = Tue, 01 Apr 1997 00:30:01 GMT
today.toLocaleString() = 03/31/97 16:30:01

Top


document object

The document object represents the entire page currently on display in the Web browser.

Syntax

The syntax for the document object is

document.propertyName

or

document.methodName(parameters)

Properties

.alinkColor Reflects the ALINK attribute of the document's <BODY> tag

anchors An array reflecting all anchors in a document

.bgColor Reflects the BGCOLOR attribute of the document's <BODY> tag

.cookie Specifies a cookie

.forms An array reflecting all forms defined within the page using <FORM> tags

.lastModified The date/time that the page was last modified

.linkColor Reflects the LINK attribute of the document's <BODY> tag

.links An array reflecting all links in a document

.location Reflects the complete URL of the current page

.referrer Reflects the URL of the calling page

.title Reflects the contents of the <TITLE> tag

.vlinkColor Reflects the VLINK attribute in the document's <BODY> tag

The anchor object, form object, history object, and link object are also properties of the document object.

Methods

.clear() Removes the page from the browser window

.close() Terminates the input stream to the page, but leaves the page displayed on the screen

.open(mimetype) Opens the input stream to a page to collect incoming write() and writeln(). If ommitted, mimetype is standard text/html

.write(string_expression) Writes string_expression directly to the page

.writeln(string_expression) Writes string_expression directly to the page and sends a line break (Unix only)

Event handlers

onLoad When used in the <BODY> tag, specifies JavaScript code to be executed as soon as the page is opened.

onUnload When used in the <BODY> tag, specifies JavaScript code to be executed as soon as the page is unloaded.

Though onLoad() and onUnload() technically are event handlers for the larger window object, you place them within the <BODY> tag of the current page.

Description

JavaScript's document object provides access to the entire Web page, including the <HEAD> section, <BODY> definition, and various objects within the page, such as anchors, forms, and links.

The document object is a property of the larger window object.

Example

<HTML>
<HEAD>
<TITLE>JavaScript Document Object</TITLE>
</HEAD>
<BODY>
<P>
Hello, my name is JavaScript Document Object and I'll be your
web page. I have two hyperlinks in me, one to <A HREF="http://www.coolnerds.com" >Alan's Coolnerds site</A>.
The other to <A HREF="http://home.netscape.com" >Netscape's home page</A>.
Below are some of the properties about me.<BR>

<P>
<SCRIPT LANGUAGE = "JavaScript"> 
        document.write ("document.bgColor = ",document.bgColor,"<BR>") 
	document.write ("document.fgColor = ",document.fgColor,"<BR>")
	document.write ("document.linkColor = ",document.linkColor,"<BR>")
	document.write ("document.alinkColor = ",document.alinkColor,"<BR>")
	document.write ("document.vlinkColor = ",document.vlinkColor,"<BR>") 
	document.write ("document.location = ",document.location,"<BR>")
	document.write ("document.lastModified = ",document.lastModified,"<BR>")
	document.write ("document.title = ",document.title,"<BR>")
</SCRIPT>
</BODY>
</HTML>

Try it


Top


elements array

The elements arrary is an array of objects corresponding to each field within a form. The first item in the array, elements[0], is the first form field. The second item, elements[1], is the second form field, and so on.

Syntax

The syntax for the elements array is

document.formName.elements[index]

or

document.formName.elements.length

where formName is either the name of a form or an element in the forms array and index is an integer representing the object's position in the array.

Properties

.length Reflects the number of fields on the form

.value Reflects the contents of one form field

The value returned by .value reflects either the contents of the field or the VALUE attribute of the field's INPUT tag, depending on the type of field being referred to.

Description

The elements array is a list that contains one item for each object (button, checkbox, hidden, password, radio, reset, select, submit, text, or textarea object) in a form. This provides an way to refer to fields in a form without using the name. For example, suppose that your document contains a form named UserInput. The first field in that form is named ReaderName. You can refer to the contents of the field using either of the following JavaScript statements:

document.UserInput.ReaderName.value

or

document.UserInput.elements[0].value

where elements[0] is the generic term for "the first field in the form."

The elements array is a property of the larger form object

Example

The following script displays a form with a final button titled Show Facts.

<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function showElements() {
     msgWindow=window.open("","displayWindow") 
     msgWindow.document.write ("<H1><CENTER>FORM FACTS</CENTER></H1><P>") 
     for (var i=0; i <= document.survey.elements.length-1;i++) {
       msgWindow.document.write ("document.survey.elements[",i,"].value",                                                  document.survey.elements[i].value,"<BR>")
     }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name = "survey"> 
     <! hidden form field> 
     <INPUT NAME="hidden" VALUE="surveyform" TYPE=HIDDEN><BR>

     <! text form field>
     Your Name: <INPUT NAME="ReaderName" VALUE="" MAXLENGTH="25" SIZE=25><P> 
     
     <! checkbox form field>
     You like JavaScript: <INPUT TYPE="CHECKBOX" NAME="LikesJavaScript" VALUE="true" CHECKED><P> 

     <! selection box form field>
     Which Browser do your use?:
     <SELECT NAME="WhichBrowser"> 
          <OPTION SELECTED VALUE="InternetExplorer">Internet Explorer 
          <OPTION VALUE="Navigator2">Navigator 2.0 
          <OPTION VALUE="other">Other 
     </SELECT>
     <P>
     <! radio button group form field>
     What kind of server do you use? : 
     <INPUT TYPE="RADIO" NAME="Server" VALUE="Own Server">Own Server 
     <INPUT TYPE="RADIO" NAME="Server" VALUE="National ISP">National ISP 
     <INPUT TYPE="RADIO" NAME="Server" VALUE="Local ISP">Local ISP 

     <! Submit and Reset buttons>
     <P>
     <INPUT TYPE=SUBMIT VALUE="Submit" NAME="submitbutton"> 
     <INPUT TYPE=RESET VALUE="Reset">
     <P><P>

     <! button to trigger showElements() custom function> 
     <INPUT TYPE="button" VALUE="Show Facts" onClick = "showElements()">
     </FORM>
     </BODY></HTML> 








Try it

Suppose that you now open this script and fill in the form that appears with the following information/selections: Name=Freddie Lame, You Like JavaScript is checked, Which Browser Do You Use is Navigator 2.0, and the Server option is Own Server. Then you click the Show Facts button. A new window appears showing the the following facts:

document.survey.elements[0].value = surveyform

document.survey.elements[1].value = Freddie Lame

document.survey.elements[2].value = true

document.survey.elements[3].value = null

document.survey.elements[4].value = Own Server

document.survey.elements[5].value = National ISP

document.survey.elements[6].value = Local ISP

document.survey.elements[7].value = Submit

document.survey.elements[8].value = Reset

document.survey.elements[9].value = Show Facts

Here you can see how the .value property depends on the type of form field being referenced. For the first two items, which are a text box and hidden text box, the value is the actual stuff in the field. Note that each radio button is considered a single object, and hence there are three elements (4-6) in the elements array. The .value of the buttons are the button titles because the button titles are defined by using the VALUE attribute in the <INPUT type='button'...> tag.

Top


escape() function

This function returns the ASCII encoding of an argument in the ISO Latin-1 character set, useful for writing cookies to the cookies.txt file.

Syntax

The syntax for the escape() function is

escape("string")

where string is any string.

Description

The escape function is not a method associated with any object but it is part of the JavaScript language. The value returned by escape() is the same string with non-alphanumeric characters encoded in the form "%xx", where xx is the ASCII encoding of a character in the string.

Example

When you run this script

<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT Language = "JavaScript">
     mystring = "Don't go away!!"document.write (escape(mystring)) 
</SCRIPT>
</BODY>
</HTML> 






the screen displays

Don%27t%20go%20away%21%21

which is "Don't go away!" with all the non-alphanumeric characters "escaped" into %xx format.

Top


eval() function

The eval() function executes a string as through it were a JavaScript statement.

Syntax

The syntax for using the eval function is

eval(string)

where string is any string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.

Description

The argument of the eval() function must be a string that can also be executed as a valid JavaScript statement. If the string represents an expression, eval() evaluates the expression. If the string is a numeric sring character, eval() returns the number. If the argument represents one or more JavaScript statements, eval() performs the statements.

Example

When executed, this script

<HTML>
<BODY>
<SCRIPT Language = "JavaScript">
     var string1 = "5 * 10"
     var string2 = "Howdy"
     var executable = "document.write('<H1><CENTER>"+string2executable += "</CENTER></H1>')"
     document.write ("eval(string1) = ",eval(string1),"<BR>")
     document.write ("eval(executable) produces ")
     eval(executable) 
</SCRIPT>
</BODY>
</HTML> 








displays this on the screen:

eval(string1) = 50

eval(executable) produces

Howdy

Try it

Top


Event handlers

Event handlers are used in HTML tags, such as <INPUT> and <BODY>, to execute JavaScript code in response to some event that occurs in the reader's page. Table 9 summarizes the event handlers, what actions trigger them, and the tags that can use them.

Table 9: Summary of JavaScript Event Handlers

Event Handler When Triggered Used in Tags of These Objects
onBlur When the reader moves the insertion point out of a field select, text, textarea
onChange After the reader changes the contents of a field and moves on to another field select, text, textarea
onClick When the reader clicks on an item button, checkbox, radio, link, reset, submit
onFocus When the reader moves the insertion point into a field select, text, textarea
onLoad When a document is loaded into view window <BODY>, <FRAMESET>
onMouseOver When reader points to a hyperlink link <A>...</A>
onSelect When the reader selects text within a text or text area field text, textarea
onSubmit When the reader submits a form form <FORM>
onUnload When the reader exits a document window <BODY>, <FRAMESET>

Top


for statement

This statement defines a loop that repeats a series of commands as long as some condition holds true.

Syntax

The syntax of for statements isfor ([intial-expression;] [condition;] [increment-expression]) { statements }

where intial-expression is an expression that sets the starting value, condition is an expression that proves true or false, increment-expression is an expression that incrememts the initial expression, and statements are Javascript statements that are executed with each pass through the loop as long as condition proves true.

Description

The for loop is generally used to set up a loop and create a counter that is incremented with each pass through the loop. The initial-expression is evaluated first, followed by the condition. If the condition proves true, then all statements within the curly braces that follow are executed once. Next, the increment-expression is executed and the condition is re-tested. When the condition proves false, the loop terminates and execution resumes just after the closing curly brace (}).

Example

When this Web page is opened in a browser

<HTML>
<BODY>
<SCRIPT Language = "JavaScript">
     for (var i=1; i <= 10; i++) {
          document.write ('i = ',i,'<br>')
     }
</SCRIPT>
</BODY>
</HTML> 






it displays:

i = 1

i = 2

i = 3

i = 4

i = 5

i = 6

i = 7

i = 8

i = 9

i = 10

because for each pass through the loop, the document.write statement writes "i = " followed by the current value of i. It then i++ increments the value in i by 1 and the loop continues as long as i is less than or equal to 10.

Try It

Top


for ... in statement

This statement iterates a value over all properties of an object.

Syntax

The syntax for this statement isfor (variable in object) { statements }

where variable is any valid variable name, object is the name of any existing object, and statements are Javascript statements that are executed as long as variable is less than or equal to the number of properties assigned to an object.

Description

All objects have properties. The for...in loop can get at those properties without using specific property names. For example, if i is the variable defined in the for...in loop, the first pass through the loop references the object's first property. The second pass through the loop references the object's second property and so on until all properties for that object have been referenced.

Example

In the following page, the custom function named dump_props writes out all properties for any object (obj) passed to it. It displays the name of the object as well via the passed obj_name argument:

<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function dump_props(obj, obj_name) {
     msgWindow=window.open("","displayWindow") 
     var result = ""
     for (var i in obj) {
          msgWindow.document.write (obj_name + "." + i + " = " + obj[i] + "<BR>") }
     }
</SCRIPT>
</HEAD>
<BODY>
<FORM name = 'testform'>
     <TEXTAREA NAME="SomeText" ROWS=3 COLS=25> type something here</TEXTAREA>
     <INPUT type="button" value="Click Me" onClick =
     dump_props(document.testform.SomeText,'SomeText')">
</FORM>
</BODY>
</HTML> 






When executed, the BODY of this script displays a form with a textarea form field and a button. Clicking that buttons calls up the dump_props function to display all properties for the document.testform.SomeText object, writing the name SomeText with each pass through the loop. The result, which is shown in the following example, is a catalog of all properties associated with the form fields. The null properties typically are properties that are not associated with this particular type of form field:

SomeText.defaultChecked = null

SomeText.checked = null

SomeText.selectedIndex = null

SomeText.options = null

SomeText.length = null

SomeText.defaultValue = type something here

SomeText.value = (whatever the reader types into the box)

SomeText.form =

SomeText.name = SomeText

Try It

Top


form object (forms array)

The form object refers to a single form within a Web page. The forms array is a list that contains one element for every form in the Web page (one element for every <FORM> tag.)

Syntax

You create a form by using Insert > Form Field in Word IA or by manually typing <FORM>...</FORM> tags into a page. To refer to a form, property, or method from within JavaScript code. you can use any of these syntaxes:

document.formName.propertyName

document.formName.methodName(parameters)

document.forms[index].propertyName

document.forms[index].methodName(parameters)

document.forms.length

where formName is the value of the NAME attribute in the <FORM> tag, propertyName is one of the pre-defined form properties, methodName is one of the pre-defined methods of forms, index is an integer representing a form object where forms[0] is the first form in the page, forms[1] is the second form in the page, and so on. The last syntax, document.forms.lengths, returns the number of forms defined within the current page (such as 1 if the page contains one form).

Properties

.action Reflects the ACTION attribute as defined in the <FORM> tag

.elements An array reflecting all the elements (fields) in the form

.encoding Reflects the ENCTYPE attribute as defined in the <FORM> tag

.length Reflects the number of elements in a single form

.method Reflects the METHOD attribute as defined in the <FORM> tag

.target Reflects the TARGET attribute as defined in the <FORM> tag

The following JavaScript objects are also properties of the form object. Each of these objects is created with <INPUT> tags that are placed between a pair of <FORM>...</FORM> tags:

button object A clickable button on the form

checkbox object A checkbox on the form

hidden object A hidden text field

password object A password box on the form

radio object A radio button on the form

reset object The form's Reset button

select object A select box (drop-list) on the form

submit object The form's Submit button

text object A text box form field

textarea object A multi-line text box form field

The forms array has one property, .length, which reflects the number of forms in a document.

Methods

.submit() When executed, it submits the form as though the reader had clicked the Submit button

Event handlers

onSubmit Triggered when the reader clicks the Submit button

Description

Each form in a document is a distinct object with a name, as defined in the NAME attribute of the form, and a number. The number is assigned automatically when the page is opened. So, for example, if the current page contains one form, but that form's <FORM> tag doesn't contain a NAME attribute, you can still refer to the form from within JavaScript code as document.forms[0].

The form object is a property of the larger document object.

Example

The page that follows illustrates the use of a form's submit() method to check the validity of entered data before submitting a form. When the reader clicks the Done button, that button's onClick event handler calls upon the checkData() function. CheckData() uses the custom contains() function to see if the reader's entry (which is supposed to be an email address) contains an @ character. If the entry doesn't contain an @ character, only the message This doesn't look like an email address to me! Nothing is submitted. If the entry does contain an @ character, the document.myform.submit() submits the form.

(This is just an example. For the submission to really happen, the <FORM> tag needs to specify where to send the submitted form.)

<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
var dataOK=false
function contains(onechar,lstring) { 
     retval = false 
     for (var i=1;i<=lstring.length;i++) {
          if (lstring.substring(i,i+1)==onechar) {
          retval=true 
          break 
          } 
     } 
     return retval
}
function checkData (){
     if (contains("@",document.myform.eaddress.value)) {
          document.myform.submit()} //submit myform.}
     else {
          alert("This doesn't look like an email address to me!")
          return false
     }
}
</SCRIPT>
<BODY>
<FORM NAME="myform">
<B>Enter your email address:</B>
     <INPUT TYPE="text" NAME="eaddress"><P>
     <INPUT TYPE="button" VALUE="Done" NAME="button1" onClick="checkData()">
</FORM>
</BODY></HTML> 






Try it

Top


frame object (frames array)

A frame is a smaller window within the larger browser window. Each frame can display a different document or URL and each frame is independently scrollable. Each frame also has its own history list. For example, to go back in a frame, the reader right-clicks the frame and chooses Back In Frame from the menu that appears.

Syntax

Frames are defined by the HTML tags <FRAMESET> and <FRAME>. See Chapters 25 and 30. You may include JavaScript onLoad and onUnload() event handlers in the <FRAMESET> tag. In JavaScript code, you can refer to frames using any of these syntaxes:

[windowReference.]frameName.propertyName

[windowReference.]frames[index].propertyName

window.propertyName

self.propertyName

parent.propertyName

where frameName is the value of the NAME attribute in the <FRAME> tag of a frame definition, index is an integer representing a frame as a number, and propertyName is any of the valid properties for frames, as follows.

The optional windowReference is a window name as defined by a var x = window.open(...) statement, or one of the synonyms top or parent..

The frames array has a length property that identifies how many child frames are in a window or frame. To access that value use either of these syntaxes:

[windowReference.].frames.length

[frameReference.].frames.length

Properties

.frames An array reflecting all the frames in a window

.name Reflects the NAME attribute as defined in the <FRAME> tag

.length Reflects the number of child frames within a frame

parent A synonym for the window or frame containing the current frameset

self A synonym for the current frame

window A synonym for the current frame

The frames array has one property:

.length Reflects the number of child frames within a frame

Methods

.clearTimeout() Cancels an ongoing timer set by the .setTimeout() method

.setTimeout() Evaluates an expression after a specified amount of time

Event handlers

Although they are (technically) event handlers of the window object, you can use the onLoad and onUnload event handlers in a <FRAMESET> tag.

Description

The <FRAMESET> tag is used in a special Web page whose sole purpose is to define a set of frames that can display documents independently of one another. Each is, to JavaScript, an independent window object.

If a <FRAME> tag contains SRC and NAME attributes, you can refer to that frame from a sibling frame by using the synonym parent to refer to the page that defined both frames - that is, the parent frame that contains the <FRAMESET> and <FRAME> tags. For example, if the third frame in a set is named mainFrame, neighboring sibling frames can refer to that frame using parent.mainframe.

JavaScript also maintains an array of frames so that you can refer to unnamed frames by number. The first frame is frames[0], the second frame is frames[1], and so on. Referring back to the preceding example, if the third frame was not given a name in its <FRAME> tag, JavaScript can still refer to it as parent.frames[2].

The top property also is a synonym that can be used in place of the frame name. The top property refers to the top-most window that contains frames or nested framesets. Thus, if one <FRAMESET> page creates another <FRAMESET> page and you are in the bottommost page, then parent refers to the page that created the frame you are in and top refers to the <FRAMESET> page that created the frames above the parent.

The self and window properties are synonyms for the current frame, and you can optionally use them to refer to the current frame (not the parent or the top frame).

The frame object is a property of the larger window object.

Example

Suppose that the following Web page is named index.html and is the first page that opens when a reader comes to this site. The page splits the browser window into a narrow window named toc (for table of contents) and a larger window named main.

<HTML>
<! Set up the frames >
<! ----- Split into two columns>
<FRAMESET COLS= "130,*">
     <FRAME NAME="toc" SRC = "places.htm" MARGINWIDTH = "0" MARGINHEIGHT="0">
     <FRAME NAME="main" SRC = "home.htm" MARGINWIDTH = "10" MARGINHEIGHT="10">
</FRAMESET>
</HTML> 






The places.htm page, which is displayed in the narrower toc frame, can control documents in the larger main frame by referring to parent.main as in the examples that follows:

<FORM>
<! Go back in main frame>
<INPUT type="button" onClick = "parent.main.history.back()">
<! Go forward in main frame>
<INPUT type="button" onClick = "parent.main.history.forward()">
</FORM> 






Top


function statement

A statement that declares a user-defined JavaScript function, typically in the <HEAD> of a Web page.

Syntax

The syntax for the function statement is

function name([param] [, param] [..., param]) {

statements

}

where name is the name that you assign to the function (cannot contain spaces, cannot be a reserved word) and the optional param statements are names that you assign to parameters that will be passed to the function with any call to the function. The params can be any combination of strings, numbers, and objects.

Description

The function() statement defines a custom JavaScript function that, once defined, can be called by any JavaScript code or event handler on the Web page. To ensure that a function is defined before it is called up, define all custom functions between the <HEAD> and </HEAD> tags of the Web page.

If you want the function to return a value, the function must include a return statement that specifies the value to return.

You cannot nest a function statement within another statement or within itself.

All parameters are passed to the function by value and any changes to the value are local to the function. In other words, if the function changes the value of the parameter, the change is not reflected globally or in the calling function. The only changed value that comes out of a function is the value specified in the return statement.

Example

The following Web page contains two custom functions named strToZero() and validate(). The strToZero takes any value, ensures that it is a number (not a string), and returns a number. If a non-numeric string value is passed to the function, the function returns the number 0.

The second function, validate(), does not return a value. Instead, it checks to see if the value passed to it is a number between 1 and 10. If the number is not between 1 and 10, the validate() function just displays the message Please enter a number between 1 and 10.

Both functions are called by the onClick event handler of a form field. Note that the strToZero() function first ensures that the user's entry is indeed a number (not a string) and that the validate() function operates upon that number.

<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
//function convert any non-numeric value to a zero.
function strToZero(anyval) { 
     anyval = ""+anyval 
     if (anyval.substring(0,1) < "0" || anyval.substring(0,1) > "9") {
          anyval = "0"
     }
     return eval(anyval)
} 

//function to ensure that number is between 1 and 10.
function validate(anynum) {
     if (anynum <1 || anynum > 10) {
          alert ("Please enter a number between 1 and 10.") 
     }
}
</SCRIPT>
</HEAD> 

<BODY>
<FORM>
Enter your rating:
<INPUT NAME = "Rating" SIZE = 2 onChange = "validate(strToZero(this.value))">
</FORM>
</BODY>
</HTML> 






Try It

Top


hidden object

A hidden object is a form field that is not visible to the reader. This object is generally used to pass information to yourself as the recipient of the form.

Syntax

To create a hidden object in a form in Word IA, select Insert > Form Field > Hidden. To manually create a hidden form field, use type="hidden" within an input tag, between a pair of <FORM> ...</FORM> tags.

To refer to a hidden object from within JavaScript code, use either of these syntaxes:

document.formName.hiddenName.propertyName

or

document.formName.elements[index].propertyName

where hiddenName is the value of the NAME attribute as defined in the hidden object's <INPUT> tag, formName is either the value of the NAME attribute of a form object or an element in the forms array, index is an integer representing the fields position in the elements array, and propertyName is one of the properties listed below.

Properties

.name reflects the NAME attribute as defined in the hidden object's <INPUT> tag.

.value reflects the current value of the hidden form field

Description

A hidden object is a form element and must be defined within a <FORM> tag. It is totally invisible on the Web page - and visible only in the document source view. Use a hidden field when you want to pass private information, such as the name of the form, to yourself along with the reader's responses to for fields.

You can programmatically change the value of the hidden object by changing its .value property.

A hidden object is a property of the larger form object.

Example

This page shows how to place a hidden field on a form using an <INPUT> tag, and then programmatically change the contents of the field. In this example, the script named stampForm() places the current date/time in the hidden field named timestamp. The function is executed as soon as the page is loaded, thanks to the onLoad event handler in the body tag.

Of course, you cannot see the contents of a hidden field, so this page has a little button that lets you peek at the hidden field's contents (your reader will never need that button). When you click the button, the showSecret() function is called up to reveal the contents of the hidden field.

<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function stampForm() { 
     rightnow = new Date() 
     document.myForm.timestamp.value = rightnow
} 

function showSecret() {
     msg = "hidden field contains " 
     msg += document.myForm.timestamp.value 
     alert (msg)
}
</SCRIPT>
</HEAD> 
<BODY onLoad = "stampForm()">
<FORM name = "myForm">
     <INPUT type = "hidden" name = "timestamp">
     <INPUT type = "button" value = "Try Me" onClick = "showSecret()">
</FORM>
</BODY></HTML> 







Notice that the actual object name, hidden, is specified only in the <INPUT> tag. To the rest of the JavaScript code, the hidden field is just another form field.

Try It

Top


history object

This object contains information on the URLs that the reader has visited within the current window. In Netscape Navigator, the history list is visible at the bottom of the Go menu.

Syntax

In JavaScript, you can use either of these syntaxes to refer to the history object:

history.propertyName

history.methodName(parameters)

where propertyName is one of the properties and methodName is one of the methods that follows.

Properties

.length Reflects the number of entries in the history object

Methods

.back() Displays the previous page in the history list, if any

.forward() Displays the next page in the listory list, if any

.go(n) Displays the page that is n pages from the current list in the page

In the last example, n can be either a positive or negative number. For example, history.go(4) moves four pages ahead in the history list, whereas history.go(-4) moves four pages back in the history list.

Description

The history object is a list of URLs that the user has visited in the current session and also in the current frame, if multiple frames are displayed on the screen. The properties and methods of this object let you move through the history list programmatically via JavaScript code.

The history object is a property of the larger document object.

Example

The following statements display a button labeled Back in the current Web page. When the reader clicks that button, the previous page in the frame named main is displayed. This example assumes that a prior page has used the <FRAMESET> and <FRAME> tags to define a frame named main.

<FORM>
<INPUT type = "button" value = "Back" onClick = "parent.main.history.back()") 
</FORM> 






Top


if statement

This statement makes a decision within a script.

Syntax

The general syntax for the if statement is

if {condition) { statements1 }[else { statements2}]

where condition is any expression that results in a true or false outcome and statements1 and statements2 are JavaScript code.

Description

When executed, the condition is evaluated and must return a true or false value. If the result is true, then the code within the first pair of curly braces ({}) (statements1) is executed. If the condition proves false, that code is ignored.

Else is optional. If included, the code within the second pair of curly braces (statements2) is executed if (and only if) the condition proves false.

You can nest if() statements, which means that either statements1 or statements2 can contain more if() statements.

When checking to see if a variable equals some value in an if() condition, be sure to use the double equal signs operator (==) rather than the single equal sign (=). To specify AND in an if() condition, use the && operator. To specify OR in an if() condition, use the || operator.

Example

In the following Web page, the genderOK() custom function converts the value passed to it to uppercase (using the toUppercase() method of the string object). The if() statement then checks to see if that string is letter M or the letter F. If it is, the function does not do anything. If the string is neither M or F, then the function displays the message Please enter M or F in the Gender box.

<HTML>

<HEAD>

<SCRIPT Language = "JavaScript">

function genderOK(anystring) {

   anystring = anystring.toUpperCase() 

   if (anystring == "M" || anystring == "F"){ 

      //do nothing } 

   else { 

      alert ("Please enter M or F") }

   }

</SCRIPT>

</HEAD> 

<BODY>
<FORM>
Gender:<INPUT name='Gender' Size = 2 onChange = "genderOK(this.value)">
Name:<INPUT name='ReaderName' Size = 20>
</FORM>
</BODY></HEAD>

Try It

Top


isNAN function

On Unix platforms, this function evaluates an argument to determine if it is NaN (not a number).

Syntax

The syntax for this function is

isNaN(testValue)

where testValue is the value you want to evaluate.

Description

isNaN is available on Unix platforms only. To convert a non-numeric value to a number 0 in the Windows platform, use the custom strToZero() function shown here:

function strToZero(anyval) { 
     anyval = ""+anyval 
     if (anyval.substring(0,1) < "0" || anyval.substring(0,1) > "9") { 
          anyval = "0" 
     } 
     return eval(anyval) 
} 






Once this function is defined in the head of a Web page, you can use the syntax strToZero(anyvalue) to ensure that anyvalue is a number. See "function statement" in this appendix for an example.

Top


link object (links array)

A link object is a piece of text or an image identified as a hypertext link within the current Web page, via <A HREF...>...</A> tags.

Syntax

Within a Web page, you use the <A HREF...>...</A> tags to define a hyperlink (that is, a link). To determine how many links are in the Web page, use the syntax

document.links.length

To refer to a specific link in the page using JavaScript code, use the syntax

document.links[index].propertyName

where index is an integer representing the link's position in the links array and propertyName is one of the valid properties for the link object.

Properties

.hash Specifies an anchor name in the URL

.host Specifies the hostname:port portion of the URL

.hostname Specifies the host and domain name, or IP address, of a network host

.href Specifies the entire URL

.pathname Specifies the URL-path portion of the URL

.port Specifies the communications port that the server uses for communications

.protocol Specifies the beginning of the URL, including the colon

.search Specifies a query target reflects the TARGET attribute

Event Handlers

Event handlers for hyperlinks are specified in the <A HREF...> tag that defines the link. Two event handlers are available:

onClick Triggered when the user clicks on the link

onMouseOver Triggered when the user points to the link

Description

When a page is opened, JavaScript automatically creates a list (array) of all hyperlinks in the page. The first hyperlink is links[0], the second one is links[1], and so on. Each link object within that array is a location object - a complete URL. Each item in the links array has the same properties as a location object. If a link object also is an anchor object, the object has entries in both the anchors and links arrays.

The link object is a property of the larger document object

Example

The most common use of link properties is simply to assign a custom status bar message to a hyperlink by specifying a custom onMouseOver() event handler. For example, in this page, when the reader points to the link to coolnerds, the status bar shows Go on - Go For It! rather than the customary hyperlink address:

<HTML>
<BODY> 
Go to <A HREF="http://www.coolnerds.com" onMouseOver="window.status='Go on - Go For It!';return true"> coolnerds</A> now.

</BODY>
</HTML> 






The ;return true statement is required to complete the statement and make sure that the message appears the moment that the mouse pointer touches the hyperlink.

Top


location object

This object contains information on the current document's URL.

Syntax

The syntax for this object is

[windowReference.]location[.propertyName]

where propertyName is one of the properties for the location object as listed in the following "Properties" section. Omitting the property name is equivalent to specifying the href property (the complete URL). The optional windowReference is a window name as defined by a var x = window.open(...) statement or one of the synonyms top or parent..

Properties

Most properties of the location object represent a different portion of the URL, in the general order of

protocol//hostname:port pathname search hash

The full set of properties is summarized here:

.hash Specifies an anchor name in the URL

.host Specifies the hostname:port portion of the URL

.hostname Specifies the host and domain name, or IP address, of a network host

.href Specifies the entire URL

.pathname Specifies the URL-path portion of the URL

.port Specifies the communications port that the server uses for communications

.protocol Specifies the beginning of the URL, including the colon

.search Specifies a query

Description

The location object represents the Location window in the browser window. Initially, its value is equal to the complete URL of the current document. But unlike the location property, which just returns the URL, the location object can be changed programmatically to display a new page in the window or frame.

The location object is contained by the window object. In a framed site, each frame has its own unique location object, which is the URL of the page being displayed within that frame (window). If you reference a location object without specifying a window, the location object represents the current location. If you reference a location object and specify a window name - for example, windowReference.location.propertyName - the location object represents the location of the specified window.

The location object is a property of the larger window object.

Example

The sample Web page that follows contains an anchor (bookmark) named Top just after the opening body tag. Near the bottom of the page is a button labeled Go To Top that, when clicked, adds the hash #Top to the Location box. When the reader clicks the button, he or she is taken back to the top of the page:

<HTML>
<BODY>
<A NAME = "Top"></A>
<H1><CENTER>I Have a Top</H1></CENTER>
Scroll down to bottom of this page to find a button
<SCRIPT Language = "JavaScript"> 
for (var i=1; i<=40;i++) {
     document.write ("keep going<p>") 
}
</SCRIPT>
<FORM name="mini1">
     <CENTER>
     <INPUT type="button" value="Go To Top" onClick = "self.location.hash = 'Top'">
     </CENTER>
</FORM>
</BODY></HTML> 







Try It

Top


Math object

The math object is a built-in object that has properties and methods for mathematical constants and functions.

Syntax

To use a Math object, follow the syntax

Math.propertyName

or

Math.methodName(parameters)

where propertyName is one of the properties of the Math object, methodName is one of the methods of the Match object, and parameters are appropriate values for the method.

Properties

.E Euler's constant (approximately 2.718).

.LN2 The natural logarithm of 2 (approximately 0.693).

.LN10 The natural logarithm of 10 (approximately 2.302).

.LOG2E The base 2 logarithm of e (approximately 1.442).

.LOG10E The base 10 logarithm of e (approximately 0.434).

.PI The ratio of the circumference of a circle to its diameter (approximately 3.14159).

.SQRT1_2 The square root of one-half; equivalently, one over the square root of two (approximately 0.707).

.SQRT2 The square root of 2 (approximately 1.414).

Methods

.abs(n) Returns the absolute value of n.

.acos (n) Returns the arcosine (in radians) of n.

.asin(n) Returns the arcsine (in radians) of n.

.atan(n) Returns the arc tangent (in radians) of n.

.ceil(n) Returns the least integer greater than or equal to n.

.cos(n) Returns the cosine of n.

.exp(n) Returns en, where n is the argument and e is Euler's constant.

.floor(n) Returns the greatest integer less than or equal to n.

.log(n) Returns the natural logarithm (base e) of n.

.max(x,y) Returns either x or or y, whichever is greater.

.min (x,y) Returns either x or or y, whichever is smaller.

.pow(x,y) returns x to the exponent power, that is, xy.

.random() Returns a random number between 0 and 1 (Unix only). See example for Windows equivalent.

.round(n) Returns the value of a n rounded to the nearest integer.

.sin(n) Returns the sine of n.

.sqrt(n) Returns the square root of n.

.tan(n) Returns the tangent of n.

Description

The Math object is a built-in JavaScript object. Note the use of the uppercase M in Math and the use of uppercase letters in all properties.

Example

Because the random() method doesn't work in Windows, you can create a custom randnum() function that returns a random number. The following Web page shows the randnum() function and includes a small form and button to test the custom function:

<HTML>
<HEAD>
<SCRIPT language = "JavaScript">
function randnum(lowest,highest) {
     retval = 0
     while ((retval < lowest) || (retval > highest)) {
          now = new Date()
          retval = Math.abs(Math.sin(now.getTime())) 
          retval = parseInt(retval * (highest+1)) 
     }
     return retval
}
</SCRIPT>
</HEAD>
<BODY>
Let's test the random number custom function, using numbers between 1 and 10.<P>
<FORM name="testForm">
     <INPUT name = "randomnum" size = 3"><P>
     <INPUT type="button" value = "Click for random number"onclick =
      "document.testForm.randomnum.value = randnum(1,10)">
</FORM>
</BODY>
</HRML> 




Try It

Top


Navigator object

This object contains information about the version of Netscape Navigator in use.

Syntax

The syntax for this object is

navigator.propertyName

where propertyName is one of the properties of the navigator object listed in the next section.

Properties

.appCodeName Returns the code name of the browser

.appName Returns the name of the browser

.appVersion Returns the version information for Navigator

.userAgent Specifies the user-agent header

Description

You can use the navigator object to determine information about which version of Netscape Navigator your reader is currently using.

Example

Opening this little page with Netscape Navigator Gold

<HTML>
<BODY>
<CENTER>
<SCRIPT Language = "JavaScript">
     document.write ("Hey, I see you're using <b>")
     document.write (navigator.appName," ",navigator.appVersion)
     document.write ("</b> aka ",navigator.appCodeName,". ")
     document.write ("Good for you!")
</SCRIPT>
</CENTER>
</BODY>
</HTML> 






causes the following message to display on the screen: Hey, I see you're using Netscape 2.01Gold (Win95; I) aka Mozilla. Good for you!

Try It

Top


New statement

This statement creates a new instance of an object type.

Syntax

The syntax for the new statement is

objectname = new objecttype (parameter1 [,parameter2] ...[,parameterN])

where objectname is the name you assign to the specific object being created, objecttype is the type of object you are creating, and parameters are properties of the object.

Description

Use the new keyword to create a new instance of an object in much the same way you would create a variable.

Example

In this example, you create a new date object named rightnow that reflects the system date and time when the page is opened. You then use the toLocaleString() method of the date object to display a message in the format Your visit begins at 04/02/97 12:30:00.

<HTML>
<BODY>
<SCRIPT language = "JavaScript"> 
     rightnow = new Date() 
     document.write ("Your visit begins at ") 
     document.write (rightnow.toLocaleString())
</SCRIPT>
</BODY>
</HTML> 




Top


parseFloat() function

This function converts a string containing numeric characters to a floating point number.

Syntax

The syntax for this function is

parseFloat(string)

where string is a string that represents the value you want to parse.

Description

parseFloat() parses its argument, a string, and returns a floating point number. If it finds a character other than a sign ( + or -), numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters.

If the first character cannot be converted to a number, parseFloat returns 0 (zero) on Windows platforms and NaN on any other platform, indicating that the value is not a number.

Example

When this small Web page is opened

<HTML>
<BODY>
<SCRIPT Language = "JavaScript">
     string1 = "123 Oak Tree Lane"
     string2 = "P.O. Box 630"
     document.write ('parseFloat(string1) = ',parseFloat(string1))
     document.write ('<BR>')
     document.write ('parseFloat(string2) = ',parseFloat(string2))
 </SCRIPT>
</BODY>
</HTML> 






it displays the following on the screen:

parseFloat(string1) = 123

parseFloat(string2) = 0

Top


parseInt() function

This function parses a string and returns an integer of the specified radix or base.

Syntax

The syntax for the function is

parseInt(string [,radix])

where string is a string that represents the value that you want to parse and radix is an integer that represents the radix of the return value.

Description

The parseInt function parses its first argument, a string, and attempts to return an integer of the specified radix (base). A radix of 10 indicates to convert to a decimal number, 8 octal, 16 hexadecimal, and so on. For radixes greater than 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores all characters from that point on. Floating point numbers are truncated to integer values. If the radix is not specified or is specified as 0, JavaScript assumes the following:

If the first character of the string cannot be converted to a number, parseInt returns one of the following values:

Example

Opening this small page

<HTML>
<BODY>
<SCRIPT Language = "JavaScript">
     string1 = "-1.987654321"
     string2 = "$500.00"
     document.write ('parseInt(string1) = ',parseInt(string1))
     document.write ('<BR>')
     document.write ('parseInt(string2) = ',parseInt(string2))
</SCRIPT>
</BODY>
</HTML> 






displays this in the Web browser screen:

parseInt(string1) = -1

parseInt(string2) = 0

Top


password object

In a form, a password object is a text field that hides the reader's entry by displaying an asterisk (*) for each character typed.

Syntax

To create a password object in Word IA, use Insert > Form Field > Text > Password. To create a password field manually, place an <INPUT type='password'...> tag between a pair of <FORM>...</FORM> tags.

To refer to a password object's properties and methods via JavaScript code, use any of these syntaxes:

passwordName.propertyName

passwordName.methodName(parameters)

formName.elements[index].propertyName

formName.elements[index].methodName(parameters)

where passwordName is the NAME attribute as defined in the password object's <INPUT> tag, formName is either the NAME attribute as defined in the <FORM> tag, or an element in the forms array, index is an integer representing the password field's position in the elements array, propertyName and methodName are any valid property/method for the password object, as listed in the next section, and parameters are any parameters that are acceptable to the method.

Properties

.defaultValue reflects the VALUE attribute as defined in the <INPUT> tag

.name reflects the NAME attribute as defined in the <INPUT> tag

.value reflects the VALUE attribute is set programmatically, but not a user's entry

Methods

.focus() moves the insertion point into the password field

.blur() moves the focus out of the password field so nothing can be typed there

.select() selects the contents of the password field.

Description

A password object is a form element that must be defined with an <INPUT> tag between a pair of <FORM>...</FORM> tags. The password object is a property of the larger form object.

Example

Oddly, there appears to be no way to test and validate a user's entry in a password field. Perhaps this is a bug that will be fixed. You still can create a password field using password in an input tag, as in the following example shows:

<FORM >
<INPUT TYPE="password" NAME="ReaderPassword"VALUE="" MAXLENGTH="16" SIZE=16 >
</FORM>




Top


radio object

This object is a single radio button (aka option button) on a form.

Syntax

In Word IA, you can choose Insert > Form Field > Radio Button Group to create a group of radio buttons on a form. Or, you can manually enter <INPUT type='radio'...> tags between a pair of <FORM>...</FORM> tags.

To access a radio button's properties and methods via JavaScript, use any of these syntaxes:

radioName[index1].propertyName

radioName[index1].methodName(parameters)

formName.elements[index2].propertyName

formName.elements[index2].methodName(parameters)

where radioName is the NAME attribute as defined in the <INPUT> tag, index1 is an integer representing a radio button in a radio group, formName is either the NAME attribute of a form object or an element in the forms array, index2 is an integer representing a radio button on a form. The elements array contains an entry for each radio button in a radio object. The propertyName, methodName, and parameters represent any of the valid properties/methods/parameters for the radio object, as listed in the following sections.

Properties

.checked Lets you see if a button is selected and programatically select a radio button

.default Reflects the CHECKED attribute of the button's <INPUT> tag

.length Reflects the number of radio buttons in a radio button group

.name Reflects the NAME attribute as defined in the button's <INPUT> tag

.value Reflects the VALUE attribute as defined in the button's <INPUT> tag

Methods

.click() Programatically clicks on the radio button

Event handlers

onClick Triggered when the reader clicks on the radio button

Description

All of the radio buttons in a radio button group use the same name property. To access the an individual radio button via JavaaScript, follow the object name with an index starting from 0, indicating the button's position in the group. But be aware that (for some totally counterintuitive reason) the items are numbered backwards. For example, take a look at the radio buttons defined in the following form:

<FORM name = "flashy">
<INPUT TYPE="RADIO" NAME="flashers" VALUE="first">first
<INPUT TYPE="RADIO" NAME="flashers" VALUE="second">second
<INPUT TYPE="RADIO" NAME="flashers" VALUE="third">third
<INPUT TYPE="RADIO" NAME="flashers" VALUE="fourth">fourth
<INPUT TYPE="RADIO" NAME="flashers" VALUE="fifth">fifth 
</FORM> 




For some odd reasone, document.flashy.flashers[0].value returns fifth, document.flashy.flashers[1].value returns fourth and document.flashy.flashers[4].value returns first. Go figure.

The radio object is a property of the larger form object.

Example

Opening the sample Web page that follows shows a simple form with two checkboxes, one labeled Female, the other labeled Male. Below the checkboxes appears a button labeled "Click Me":

<HTML>
<HEAD>
<SCRIPT Language = "JavaScript"> 
function showChoice() {
     var msg = "" 
     if (document.ReaderInfo.gender[1].checked) {
          msg = 'Female'
     } 
     if (document.ReaderInfo.gender[0].checked) {
          msg = 'Male'
     } 
     alert ("You chose "+msg)
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name = "ReaderInfo">
     <INPUT TYPE="RADIO" NAME="gender" VALUE="Female">Female<BR>
     <INPUT TYPE="RADIO" NAME="gender" VALUE="Male">Male<BR><P>
     <INPUT type="button" value="Click Me" onClick="showChoice()"> 
</FORM>
</BODY>
</HTML> 






When the reader clicks on the button, an alert message shows which choice he/she made in the radio buttons. The showMessage() custom function determines which choice was made by inspecting the .checked property of each radio button and assigning a value to the variable named msg when it finds the checked button. The alert() property just shows that message on the screen.

Try It

Top


Reserved words

These words have special meaning in JavaScript and cannot be used as variable names, function names, methods, or object names. Some are not used in current JavaScript but are reserved for future use.

Abstract

float

public

boolean

for

return

break

function

short

byte

goto

static

case

if

super

catch

implements

switch

char

import

synchronized

class

in

this

const

instanceof

throw

continue

int

throws

default

interface

transient

do

long

true

double

native

try

else

new

var

extends

null

void

false

package

while

final

private

with

finally

protected

Top


Reset object

This object refers to the Reset button on a form.

Syntax

To define a Reset button on a form, use the standard HTML <INPUT> tag with the type attribute set to Reset. You can add an onClick handler to trigger some JavaScript code when the user clicks the Reset button.

To access a Reset button's properties and methods from JavaScript, use any or these syntaxes:

resetName.propertyName

resetName.methodName(parameters)

formName.elements[index].propertyName

formName.elements[index].methodName(parameters)

where resetName is the NAME attribute as defined in the button's <INPUT> tag, formName is the name of the form as defined in the NAME attribute of the <FORM> tag (or an element in the forms array), index is an integer representing the reset button's position in the forms array, and propertyName, methodName, and parameters is any valid property, method, or parameter listed in the following sections.

Properties

.name Reflects the NAME attribute defined in the button's <INPUT> tag

.value Reflects the VALUE attribute defined in the button's <INPUT> tag

Methods

.click() Programmatically clicks the Reset button

Event handlers

onClick Triggered when the reader clicks on the Reset button

Description

When the Reset button is clicked, all fields in the form are emptied or returned to their default values. There is no way to stop this from happening. The onClick event handler cannot prevent a form from being reset.

The reset object is a property of the larger form object.

Example

This little Web page contains a regular form and Reset button. But when the reader clicks the Reset button, a small message appears telling the reader that all fields have been returned to their default values.

<HTML>
<BODY>
<FORM name = "ReaderInfo">
<INPUT NAME="Your Name:" VALUE="type your name here"MAXLENGTH="50" SIZE=50>
<P>
<INPUT NAME="EmailAdd" VALUE="type email address here"MAXLENGTH="40" SIZE=40>
<P>
<INPUT type="reset" onClick="alert ('Returned all fields to default values')">
</FORM>
</BODY>
</HTML>




Try It

Top


return statement

This statement returns a value to a statement that called a custom function. Used only within a custom function.

Syntax

The syntax for a return statement is

return value

where value is a value to return, or the name of a variable that contains the value to return.

Description

The return statement returns a value to whatever statement called it. If you want to base the return value on a decision, store the return value in a variable and return the variable at the end of the function.

Example

The following custom function sets a variable named retval to false. Then it loops through a large string (largestr) to see if one of its characters matches the character passed as onechar. If so, it changes the value of retval to true. When the function is finished, it returns the value of the retval variable to the calling statement.

<SCRIPT Language = "JavaScript">
function contains (onechar,largestr) {
retval = false 
     for (var i=0;i<=largestr.length-1;i++) { 
          if (largestr.charAt(i) == onechar) { 
               retval = true break 
          }
     }
return retval
}
</SCRIPT> 






Top


select object (options array)

A select object is one selection box (drop-down list) on a form.

Syntax

To access a select box's object's properties and methods from JavaScript, use any one of these syntaxes:

selectName.propertyName

selectName.methodName(parameters)

formName.elements[index].propertyName

formName.elements[index].methodName(parameters)

where selectName is the NAME attribute as defined in the <SELECT> tag, formName is the NAME attribute as defined in the <FORM> tag (or an element in the forms array), index is an integer representing the fields position in the elements array, propertyName, methodName, and parameters are any valid options for the Select object as defined in the next sections.

To get to the specific options within a select box, use one of these syntaxes:

selectName.options[index1].propertyName

formName.elements[index2].options[index1].propertyName

where selectName is the NAME attribute as defined in the <SELECT> tag, index1 is the option's position within the <SELECT > tag (starting at 0), formName is the NAME attribute as defined in the <FORM> tag (or an element in the forms array), index2 is an integer representing the select field's position in the form, and propertyName is one of the valid properties for the options array as defined in the following sections.

You can refer to options in the <SELECT> tag's options list using any of these syntaxes:

selectName.options

selectName.options[index]

selectName.options.length

where selectName is the NAME attribute as defined in the <SELECT> tag, index is the option's position in the <OPTION> list. The .length property returns the total number of options within the <SELECT> tag.

Properties

The select object has the following properties:

.length Reflects the number of options in a select object

.name Reflects the NAME attribute as defined in the <SELECT> tag

.options Reflects the <OPTION> tags

.selectedIndex Reflects the numeric index of the selected option, or the first selected option if multiple options are selected

The options array has the following properties:

.defaultSelected Reflects the SELECTED attribute as defined in the <OPTIONS> list

.index Reflects the position of an option within the list

.length Reflects the number of options in the select box

.name Reflects the NAME attribute as defined in the <SELECT> tag.

.selected Lets you programatically select an option

.selectedIndex Reflects the position of the selected option in the options list

.text Reflects the textToDisplay that follows an <OPTION> tag

.value Reflects the VALUE attribute as defined in the <OPTION> tag

Methods

.blur() Removes the focus from the select box

.focus() Moves the focus to the select box

Event handlers

onBlur Triggered when the reader moves the insertion point out of the select box.

onChange Triggered when the reader moves the insertion point out the to select box after having changed the contents of the select box

onFocus Triggered when the reader first puts the insertion point into the select box

Description

To create a select box in Word IA, choose Insert > Form Field > Selection. To create a selection box manually, type in a complete <SELECT>...</SELECT> tag between a pair of <FORM>...</FORM> tags.

You can reference the options of a select object in your code by using the options array. This array contains an entry for each <OPTION> option in the <SELECT> tag, where the first item is .options[0].

Even though each element in the options array represents a select option, the value of options[index] is always null. The value returned by selectName.options represents the full HTML statement for the selectName object. Elements in the options array are read-only. For example, the statement myDrop.options[0]="pick me" has no effect.

The select object is a property of the form object. The options array is a property of select object.

Example

The following Web page defines a custom function named showFacts() whose sole purpose is to display a bunch of information about a select box named mySelect in a form named test. The select box itself is defined in <FORM> tags in the body of the page.

<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function showFacts() {
  factswindow = window.open("","Facts") 
  factswindow.document.write("<b>Facts about the Select Box</b><p>") 
  factswindow.document.write ('document.test.mySelect.name =
      ',document.test.mySelect.name,'<br>')   
  factswindow.document.write ('document.test.mySelect.length =
      ',document.test.mySelect.length,'<br>')
  factswindow.document.write ('document.test.mySelect.options =
      ',document.test.mySelect.options,'<br>') 
  factswindow.document.write ('document.test.mySelect.selectedIndex =
     ',document.test.mySelect.selectedIndex, '<p>') 
  factswindow.document.write("<b>Facts about the Options Array</b><p>") 
  var howmany = document.test.mySelect.options.length 
  var biggest = howmany - 1 
  factswindow.document.write ('document.test.mySelect.options.length = ',howmany,'<p>') 
  for (var i=0; i<= biggest; i++) { 
     factswindow.document.write ('document.test.mySelect.options[',i,'].selected = 
      ',document.test.mySelect.options[i].selected, '<br>')
     factswindow.document.write ('document.test.mySelect.options[',i,'].defaultSelected = 
      ',document.test.mySelect.options[i].defaultSelected,'<br>') 
     factswindow.document.write ('document.test.mySelect.options[',i,'].index = 
      ',document.test.mySelect.options[i].index, '<br>')
     factswindow.document.write ('document.test.mySelect.options[',i,'].value = 
      ',document.test.mySelect.options[i].value,'<br>') factswindow.document.write ('<p>') 
   }
factswindow.document.close()
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name = "test">
<SELECT NAME="mySelect" > 
<OPTION SELECTED VALUE="1">first choice 
<OPTION VALUE="2">second choice 
<OPTION VALUE="3">third choice 
<OPTION VALUE="4">fourth choice
</SELECT>
<P>
<INPUT type="button" value = "Click me for Facts" onClick = "showFacts()">
</FORM>
</BODY>
</HTML> 




When you open this page, just the select box and a button are displayed. You can make a choice from the select box, then click the button. Clicking the button triggers the showFacts() function which displays lots of information about the current status of the select box. For example, if you choose third choice from the select box, then click on the button, the screen displays all information about the select box, and its options array.

Facts about the Select Box
document.test.mySelect.name = mySelect
document.test.mySelect.length = 4
document.test.mySelect.options = first choice second choice third choice fourth choice
document.test.mySelect.selectedIndex = 2

Facts about the Options Array
document.test.mySelect.options.length = 4
document.test.mySelect.options[0].selected = false
document.test.mySelect.options[0].defaultSelected = true
document.test.mySelect.options[0].index = 0
document.test.mySelect.options[0].value = 1
document.test.mySelect.options[1].selected = false
document.test.mySelect.options[1].defaultSelected = false
document.test.mySelect.options[1].index = 1
document.test.mySelect.options[1].value = 2
document.test.mySelect.options[2].selected = true
document.test.mySelect.options[2].defaultSelected = false
document.test.mySelect.options[2].index = 2
document.test.mySelect.options[2].value = 3
document.test.mySelect.options[3].selected = false
document.test.mySelect.options[3].defaultSelected = false
document.test.mySelect.options[3].index = 3
document.test.mySelect.options[3].value = 4

Try it

Top


string object

A string is any series of characters, such as "Joan Doe," as opposed to a number like 123.45. All strings, in JavaScript, are string objects.

Syntax

To use the properties and methods of the string object, use either of these syntaxes:

stringName.propertyName

or

stringName.methodName(parameters)

where stringName is the name of a string variable that contains a string, and propertyName, methodName, and parameters are any of the valid options listed below.

Properties

.length Reflects the length of the string

Methods

.anchor(name) Programatically creates an anchor

.big() Displays string in big font size

.blink() Causes the string to blink

.bold() Displays string in boldface

.charAt(n) Displays the character at position n in the string, where the first charater is number 0

.fixed() Displays string in fixed-pitch font

.fontcolor(color) Displays string in color where color is any valid Color Value

.fontsize(n) Displays string in relative font size n where n is a value between 1 and 7

.indexOf(smallstring,start) Returns the position of the first occurrence of smallstring within the larger string, beginning the search at the start value

.italics() Displays the string in italics

.lastIndexOf() Returns the position of the last occurrence of smallstring within the larger string, beginning the search at the start value

.link(URL) Converts string to a hyperlink with the target specified in URL

.small() Displays string in small text size

.strike() Displays string in strikeout font

.sub() Displays string as a subscript

.substring(x,y) Displays a portion of string starting at character x going to character y where the first character is number 0.

.sup() Displays string as a superscript

.toLowerCase() Displays string in all lowercase letters

.toUpperCase() Displays string in all uppercase letters

Description

A string can be represented as a literal enclosed by single or double quotes. For example, both of the following statements assign the string Howie Doone to a variable named UserName:

var UserName = "Howie Doone"

var UserName = 'Howie Doone'

You can alternate single and double quotation marks to place one type of quotation mark within the string. For example, these two JavaScript statements

var msg = 'I said "Hello" but you ignored me.'

document.write (msg)

display this on the screen:

I said "Hello" but you ignored me.

Strings can be concatenated (stuck together) and you can mix variables and literals using a plus (+) operator. For example, these commands

var x = "Hello"
var y = "There"
var z = x + " " + y + "!"
document.write (x)

will display this on the screen:

Hello There!

Example

Opening the following Web page

<HTML><BODY>
<SCRIPT Language = "JavaScript">
var fullname = "Angie Myma"
document.write ("fullname = ",fullname,'<br>')
document.write ("fullname.length = ",fullname.length,'<br>')
document.write ("fullname.bold() = ",fullname.bold(),'<br>')
document.write ("fullname.italics() = ",fullname.italics(),'<br>')
document.write ("fullname.charAt(6) = ",fullname.charAt(6),'<br>')
document.write ("fullname.toLowerCase() = ",fullname.toLowerCase(),'<br>')
document.write ("fullname.toUpperCase() = ",fullname.toUpperCase(),'<br>')
</SCRIPT> 
</BODY></HTML> 


displays the following on the screen:

fullname = Angie Myma

fullname.length = 10

fullname.bold() = Angie Myma

fullname.italics() = Angie Myma

fullname.charAt(6) = M

fullname.toLowerCase() = angie myma

fullname.toUpperCase() = ANGIE MYMA

Try It

Top


submit object

The submit object refers to the Submit button on a form. Clicking the button causes the form to be submitted to whatever address is specified in the button's <FORM> tag.

Syntax

To create a Submit button in Word IA, choose Insert > Form Field > Submit Button. To create a Submit button, manually use the TYPE="submit" attribute in an <INPUT> tag between a pair for <FORM>...</FORM> tags.

To get at a Submit button's properties and methods from JavaScript code, use any one of these syntaxes:

submitName.propertyName

submitName.methodName(parameters)

formName.elements[index].propertyName

formName.elements[index].methodName(parameters)

where submitName is the NAME attribute of the button as defined in its <INPUT> tag, formName is the name of the form as defined in the <FORM> tag (or an element in the forms array), index is an integer representing the submit button's position on the form, and propertyName, methodName and parameters are valid options for the submit object as listed below.

Properties

.name Reflects the NAME attribute as defined in the button's <INPUT> tag

.value Reflects the VALUE attribute as defined in the button's <INPUT> tag

Methods

.click() Programatically clicks the button

Event Handlers

onClick Triggered when the reader clicks the Submit button

Description

A form's Submit button must be defined with an <INPUT> tag within the form's <FORM>...</FORM> tags. Clicking the Submit button submits a form to the URL specified by the form's ACTION action attribute.

The onClick event handler for a Submit button cannot prevent a form from being submitted. However, the form's onSubmit event handler, and the form's submit method, can be used to submit an object from a regular button.

The submit object is a property of the larger form object.

Example

The Submit button gets information on where to send the form's data from the ACTION, METHOD, and ENCTYPE attributes of <FORM> tag that houses the button. In the example below, clicking the Submit button will send the data from the form to my e-mail address at alan@coolnerds.com.

<HTML>
<BODY>
<FONT SIZE=6 COLOR=#0000FF>Ask Alan</FONT><BR>
<FORM METHOD=POST ACTION="/cgi-bin/mailto?alan@coolnerds.com:Ask_Alan">
<P>
Question:<TEXTAREA NAME="01Question" ROWS=5 COLS=80></TEXTAREA>
<P>
My e-mail address is: <INPUT NAME="02ReturnAdd"VALUE="" MAXLENGTH="70" SIZE=70>
<P>
<INPUT TYPE="SUBMIT" VALUE="Submit">
<INPUT TYPE="RESET">
<BR>
</FORM>
</BODY></HTML> 




Top


text object

A text object is a single text field in a form.

Syntax

To create a text field in Word IA, choose Insert > Form Field > Text from Word IA's menu bar. To create a form field manually, type an <INPUT> tag between a pair of <FORM>...</FORM> tags. To refer to a text box field from JavaScript code use any of these syntaxes:

textName.propertyName

textName.methodName(parameters)

formName.elements[index].propertyName

formName.elements[index].methodName(parameters)

where textName is the NAME attribute as defined in the <INPUT> tag, formName is the NAME attribute as defined in the <FORM> tag, (or an element in the forms array), index is an integer representing the field's position on the form, propertyName, methodName, and parameters are the valid options listed in the next sections.

Properties

.defaultValue Reflects the VALUE attribute as defined in the field's <INPUT> tag

.name Reflects the NAME attribute as defined in the field's <INPUT> tag

.value Reflects the current value (contents) of the text field

Methods

.focus() Moves the focus into the text field

.blur() Moves the focus out of the text field

.select() Selects the contents of the text field

Event handlers

onBlur Triggered when the reader leaves the text field

onChange Triggered when the reader makes a change then leaves the text field

onFocus Triggered when the reader enters the text field

onSelect Triggered when the reader selects text in the text field

Description

You can use JavaScript code to test and to change text in a text form field.

The text object is a property of the larger form object.

Example

In the following Web page, a custom function named pcase() is defined. This function accepts any string and converts it to proper-noun case (that is, converts wAndA bEA nOId to Wanda Bea Noid. The first text box in the form, located down in the body of the page, calls up the pcase() function to change whatever the reader types into the fullname field to proper case:

<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
//custom function to convert text to proper-noun case (initial caps).
function pcase(str) { 
   strlen = str.length 
   jj = str.substring(0,1).toUpperCase() 
   jj = jj + str.substring(1,strlen).toLowerCase() 
   for (i = 2; i <= strlen; i++) { 
      if (jj.charAt(i)==" ") { 
         lefthalf = jj.substring(0,i+1) 
         righthalf = jj.substring(i+1,strlen) 
         righthalf = righthalf.substring(0,1).toUpperCase()+righthalf.substring(1,strlen) 
         jj=lefthalf+righthalf 
      } 
   } 
   return jj
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>Type your full name: 
<INPUT NAME="fullname" VALUE="" MAXLENGTH="50" SIZE=50 
   onChange = "this.value = pcase(this.value)">
<P> 
Type your address: <INPUT NAME="address" VALUE="" MAXLENGTH="50" SIZE=50>
<P>
</FORM>
</BODY></HTML> 


Try it

Top


textarea object

A textarea object is one multiline text field in a form.

Syntax

To create a textarea field on a form using Word IA, choose Insert > Form Field > Text > OK > Multiple Line. To manually create a textarea field, type HTML <TEXTAREA>...</TEXTAREA> tags within a pair of <FORM>...</FORM> tags. To access a textarea field from JavaScript code, use any one of these syntaxes:

textareaName.propertyName

textareaName.methodName(parameters)

formName.elements[index].propertyName

formName.elements[index].methodName(parameters)

where textareaName is the NAME attribute as defined in the <TEXTAREA> tag, formName is the name of the form as defined in the NAME attribute of the <FORM> tag (or an element in the forms array), index is an integer representing a textarea field's position on the form, and propertyName, methodName, and parameters are any of the valid options listed in the next sections.

Properties

.defaultValue Reflects the VALUE attribute as defined in the <TEXTAREA> tag

.name Reflects the NAME attribute as defined in the <TEXTAREA> tag

.value Reflects the current value of the textarea object

Methods

.focus() moves the focus into the textarea field

.blur() moves the focus out of the textarea field

.select() selects the text in the texarea field

Event handlers

onBlur Triggered when the reader leaves the textarea field

onChange Triggered when the reader changes the contents of the textarea field then leaves the field

onFocus Triggered when the reader moves the insertion point into the textarea field

onSelect Triggered when the reader selects text in the field

Description

With JavaScript code, you can test the value of a textarea field and change its contents. When writing to a textarea field, you can begin a new line using the newline character. In Windows, the newline character is \r\n. In Unix and Macintosh, it is \n. You can use the .appVersion property of the navigator object to test for the operating system in use.

The textarea object is a property of the larger form object.

Example

The following page first defines a custom function named noBlanksAllowed that tests the value of anyval passed to it. If anyval is blank (""), it displays a warning and moves the focus into a form field named question on a form named askme.

The form and field are created in the body of the document and two events are used to trigger the noBlanksAllowed function: when the reader leaves the field named question and when the reader clicks on the button labeled Click Me. In either case, if the question textarea field is empty when the event occurs, the Please don't leave the question blank! alert message appears.

<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function noBlanksAllowed(anyval) {
   if (anyval == "") {
      document.askme.question.setFocus alert ("Please don't leave the question blank!") 
   }
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name = "askme">
Question:<BR>
<TEXTAREA NAME="question" ROWS=4 COLS=25 onChange = "noBlanksAllowed(this.value)">
</TEXTAREA><P>
Your Name:
<INPUT NAME = "readername"><P>
<INPUT TYPE="button" value = "Click Me" onClick =
   noBlanksAllowed(document.askme.question.value)">
</FORM>
</BODY>
</HTML> 


Try It

Top


this keyword

The keyword this is a synonym for the current object and can be used with properties. For example, this.value can mean the data currently in this form field.

Syntax

The syntax for this is

this.[propertyname]

where propertyname is a valid property of the current object type.

Description

The keyword this actually refers to the entire HTML tag for the object to which it refers. For example, if used in an event handler of an <INPUT> tag, the term this refers to the entire HTML <INPUT...> tag.

In the preceding example for the textarea object, we used the keyword this. to refer to the contents of the textarea field when calling the noBlanksAllowed function. However, we couldn't use this. when calling that function from the Click Me button - in the <INPUT> tag for the Click Me button, this. would refer to the button, not to the textarea field. Rather than using this., we had to spell out the reference using document.formname.fieldname as below:

<FORM name = "askme">
Question:<BR>
<TEXTAREA NAME="question" ROWS=4 COLS=25 onChange = "noBlanksAllowed(this.value)">
</TEXTAREA>
<!..other tags..>
<INPUT TYPE="button" value = "Click Me" onClick =
 "noBlanksAllowed(document.askme.question.value)"> 
</FORM> 





Example

The next page we could call WhatsTheMeaningOfThis.htm because all it really does is show the meaning of this. in an alert box. It is not very practical, but it does provide some insight.

<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
//custom function just to display the meaning of 'this.'
function showme(obj) { 
     //show what's in obj 
   var msg = "obj = "+obj 
   alert (msg) 
   //show what's in obj.name 
   var msg = "obj.name = "+obj.name 
   alert (msg) 
   //show what's in obj.value 
   var msg = "obj.value = "+obj.value 
   alert (msg)
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<INPUT type="button" name = "Fred" value="Click Me" onClick = "showme(this)">
</FORM>
</BODY>
</HTML> 




When the reader clicks on the button, the <INPUT> tag calls up the showme() function, sending it the keyword this as its parameter. The function stores that parameter in a local variable named obj. Then a series of alert boxes show some information about the obj variable. The first alert box shows

obj = <input type="button" name="Fred" value="Click Me" onClick = 'showme(this)';>

because obj currently contains the entire definition of the object passed as this. Subsequent alert boxes show individual properties of this larger object. For instance, the second alert box shows

obj.name = Fred

because Fred is indeed the NAME attribute as defined in this object. The next alert box shows

obj.value=Click Me

because the VALUE attribute in this object is defined as Click Me.

Try It

Top


unescape() function

This function returns the ASCII string for an escaped character.

Syntax

The syntax for this function is

unescape("string")

where string is a string containing characters in either of the following forms:

"%integer", where integer is a number between 0 and 255 (decimal)

"hex", where hex is a number between 0x0 and 0xFF (hexadecimal)

Description

The unescape function generally is used to convert a string that has been escaped using the escape() function to normal text. For example, you might escape a string to store it in a document cookie. Upon retrieving that string, you'd use the unescape() function to convert the string back to regular English.

Example

This small page stores an escaped string in a variable named Encoded and displays that text on the screen. A second document.write statement then displays the unescaped version of the Encoded variable:

<HTML>
<BODY>
<SCRIPT Language = "JavaScript">
var English = "Howdy Folks!"
var Encoded = escape(English)
document.write ("Encoded = ",Encoded,'<br>')
document.write ("unescape(Encoded) = ",unescape(Encoded)) 
</SCRIPT>
</BODY>
</HTML> 




The result on the screen is

Encoded = Howdy%20Folks%21
unescape(Encoded) = Howdy Folks!

Top


var statement

This statement is an optional statement used to create a new variable.

Syntax

The syntax for this statement is

var varname [= value] [..., varname [= value] ]

where varname is a variable name you create (it cannot contain spaces and cannot be a Reserved Word) and value is a value to store in the variable, or an expression that results in some value.

Description

In most cases, the var statement is optional. For example, these two statements are equivalent:var x = 10 x = 10

Both put the value 10 in a variable named x. If x does not already exist, it is created on the spot.

The scope of a variable is local to the function in which it is created. For example, if a custom function creates a variable y, that variable exists only while the function is being executed. When the function completes its task, the variable y ceases to exist.

To create a global variable - one that is accessible to multiple functions in a page, you must declare that variable outside of any function. Typically, you do so just under the <SCRIPT> tag in the head of a page before the first custom function is defined.

All variables are local to the current page. To extend a variable's scope to other pages, you need to copy the variable to a document cookie. See Chapter 31 in HTML Publishing Bible for more information on local and global variables, and cookies.

Example

This code snippet, taken from the sample form described in Chapter 32 of HTML Publishing Bible, declares several global variables near the top of the first script in this page's <HEAD> section:

<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
//Global Variables
var RowsInForm = 5
var ProductsInList = 10
var SalesTaxRate = 0.0775
var TaxableState = "CA"
var ProdSubscript = 0 





Top


while statement

This statement defines a loop that is executed until some condition proves false. Generally used when no incrementing counter is needed.

Syntax

The syntax for the while statement is as follows:

while (condition) {

statements

}

where condition is an expression that evaluates to true or false and statements are any number of Javascript statements.

Description

A while loop is similar to a for loop except that there is no automatically incremented counter in the loop. The condition statement is evaluated once at the start of the loop, then each time execution passes through the loop. If condition proves true, code within the curly braces is executed. If condition proves false, code within the curly braces is ignored and execution resumes with the first statement after the closing curly brace (}).

Example

In the following code snippet, a while loop repeats a series of JavaScript statements until they come up with a random number that's between 1 and 10 (inclusive):

<SCRIPT Language = "JavaScript">
randomNumber = 0
while ((randomNumber < 1) || (randomNumber > 10)) { 
     now = new Date() 
     randomNumber = Math.abs(Math.sin(now.getTime())) 
     randomNumber = parseInt(randomNumber * 10.5) }
     document.write ('random number = ',randomNumber) 
</SCRIPT> 




Try It

Top


window object

A window object is the top-level object for each document, location, and history object.

Syntax

To open a new window, use the following syntax:

[windowVar = ][window].open("URL", "windowName", ["windowFeatures"])

where windowVar is a name that you create for the new window and also the name you will use when referring to a window's properties, methods, and containership in JavaScript code. URL specifies the URL to open in the new window. It can be null ("") to open a window with no document. The windowName portion represents the window name to use in the TARGET attribute of a <FORM> or <A> tag. The optional windowFeatures is a comma-separated list of any of the following options and values:

toolbar[=yes|no]| or [=1|0] Display Navigator window toolbar?

location[=yes|no] or [=1|0] Display Navigator window Location: box?

directories[=yes|no] or [=1|0] Display Navigator window directory buttons?

status[=yes|no] or [=1|0] Display Navigator window status bar?

menubar[=yes|no] or [=1|0] Display Navigator window menu bar?

scrollbars[=yes|no] or [=1|0] Display Navigator window scrollbars?

resizable[=yes|no] or [=1|0] Make window resizeable?

width=pixels Width of the window

height=pixels Height of the window

where pixels is a positive integer specifying the dimension in pixels. You may use any subset of these options. Separate options with a comma. Do not put spaces between the options. Enclose the entire set of options in a pair of single quotation marks.

To refer to an opened window's properties and methods in JavaScript code, use any of these syntaxes:

window.propertyName

window.methodName(parameters)

self.propertyName

self.methodName(parameters)

top.propertyName

top.methodName(parameters)

parent.propertyName

parent.methodName(parameters)

windowVar.propertyName

windowVar.methodName(parameters)

propertyName

methodName(parameters)

where windowVar is the variable created when the window was opened, propertyName, methodName, and parameters are valid options for the window object as listed in the following sections.

Properties

.defaultStatus Reflects the default message displayed in the window's status bar

.frames An array reflecting all the frames in a window

.length Reflects the number of frames in a parent window

.name Reflects the windowName argument

.parent Refers to a window containing a <FRAMESET> tags

.self Refers to the current window

.status Specifies message to display in the window's status bar

.top Refers to the top-most Navigator window

.window Refers to the current window

.document Refers to the document on display within the window

.frame Refers to an independently-scollable frame created with a <FRAME> tag

.location Contains information on the URL of the document displayed in the window

Methods

.alert("msg") Displays a JavaScript alert message box with msg and OK button

.close() Closes the window

confirm("msg") Displays a JavaScript confirm message box with msg and OK and Cancel buttons

.open("URL", "windowName", ["windowFeatures"]) Opens a window displaying URL with windowName as target name and optional windowFeatures

prompt("msg",["default"]) Displays a JavaScript prompt box with msg and optional default text

timerID = setTimeout(exp,msec) Delays execution of expression msec milliseconds

clearTimeout(timerid) Cancels timerid created by setTimeOut()

Event handlers

onLoad Defined in a <BODY> or <FRAMESET> tag

onUnload Defined in a <BODY> or <FRAMESET> tag

Description

The window object is the top-level object in the JavaScript object hierarchy. Frame objects are also windows. The self and window properties are synonyms for the current window, and you can use them to refer to the current window. For example, you can close the current window by calling either window.close() or self.close().

The top and parent properties also are synonyms that can be used in place of the window name. The top property refers to the top-most Navigator window and parent refers to a window containing a frameset.

Because the existence of the current window is assumed, you do not have to reference the name of the window when you call its methods and assign its properties. For example, even though the document is an object of the larger window object, it is not necessary to precede every document statement with a window name. For example, document.write("Howdy") is valid. The omission of a window name before the document name just assumes that the document object being referred to is the document in the current window.

On the other hand, when using the open() and close() methods in event handlers, you should always specify window or self. Otherwise, close() by itself just closes the input stream to the current document. For example, if you want a button to close the entire window that houses the button, the onClick event handler for that button should be self.close() rather than close().

Although technically, the onLoad and onUnload event handlers are part of the window object, the window object has no event handler until an HTML <BODY> or <FRAMESET> tag is written to the window. The onLoad and onUnload event handlers can be specified within those tags.

Example

In the following example, the myMsgBox() custom function is capable of displaying a small window that shows a message and OK button. This window can be used as an alternative to the JavaScript alert() message box. The body of the page contains a button that tests the custom function by calling upon it to display the message Howdy World!:

<HTML>
<HEAD>
<SCRIPT Language = "JavaScript">
function myMsgBox(msg) {
//set up window options
stats='toolbar=no,location=no,directories=no,status=no,menubar=no,'
stats += 'scrollbars=no,resizable=no,width=200,height=100'
//open the window
MsgBox = window.open ("","msgWindow",stats)
//set window back color, text color, show msg, and OK button.
MsgBox.document.write ("<BODY bgColor='black' text='white'>")
MsgBox.document.write ("<H2><CENTER>",msg,"</CENTER></H2>")
MsgBox.document.write ("<FORM><CENTER>")
//when reader clicks the OK button in this message window, close the message window.
MsgBox.document.write ("<INPUT type='button' value='OK' onClick = 'self.close()'>")
MsgBox.document.write ("</CENTER></FORM>")
}
</SCRIPT>
</HEAD>

<BODY>
<FORM>
<! Call upon myMsgBox to display a "Howdy World" message.>
<INPUT type='button' value = 'Click me to see a custom message window'
onClick = 'myMsgBox("Howdy World")'>
</FORM>
</BODY>
</HTML>

Try It

Top


with statement

This statement sets up a default object for a set of statements.

Syntax

The syntax for this statement is as follows:

with (object) {

statements

}

where object is the name of a specific object and statements are Javascript statements to be executed.

Description

Use with as an alternative to a series of lengthy object names or this. keywords.

Example

As an alternative to restating the Math. object name repeatedly in the statements, as shown here:

radius = 5.4
area = Math.PI * (radius*radius)
cosinePI = Math.cos(Math.PI/2)
sinePIdiv2 = Math.sin(Math.PI/2)

You can just use with(Math) and enclose the statements in a pair of curly braces, as shown in the following example:

radius = 5.4
with (Math) {
area = PI * (radius*radius)
cosinePI = cos(PI/2)
sinePIdiv2 = sin(PI/2)
}

Top


About this Document

This Coolnerds JavaScript Reference (c)Alan Simpson, 1998. Email to alan@coolnerds.com or stop by www.coolnerds.com.

Top


Warnings

JavaScript is Case Sensitive! Everything in JavaScript is case sensitive. So you have to be very careful about upper / lowercase letters in statements, variable names, properties, methods, and so forth. For example, this statement:

Document.write("Hello World")

results in the puzzling error message "Document object does not exist." However, the only problem is the uppercase D. This statement:

document.write("Hello World")

works fine.

<IMG> tags in same document can cause total weirdness! Many people have reported that if a page contains pictures (i.e. <IMG SRC> tags), and JavaScript code, the code behaves very strangely. The (peculiar) fix is to make sure that every <IMG SRC> tag contains a HEIGHT and WIDTH attribute.

JavaScript changes! Like everything else on the Internet, JavaScript is always evolving and changing. Therefore, the Internet itself is your best resource for current information.

Try It's Can Fail You can browse the JavaScript reference with any web browsers. But the Try It options will work only in JavaScript-capable browsers. They will act very weird (or not at all) in non-JavaScript capable browsers!

Top