You are on page 1of 23

JavaScript Objects JavaScript uses objects to perform many tasks and is considered an object-based programming language.

The language has many built-in objects and also allows custom objects to be created. A reference of common, built-in objects is available.

Definition of an Object
In effect, an object is a grouping of datum and functions that are used to describe a thing. Each datum is typically a single piece of information. Functions, on the other hand, manipulate the data. An object may have many pieces of data many functions. For example, a circle could be considered an object. It has data (radius) and it may have functions (calculate perimeter, calculate area). A car also could be considered an object. Possible data contained within a car attribute could be weight, number of doors, color, type of transmission, etc. Possible functions could be unlock doors, change gears, stop, etc. In computer science terms, an object encapsulates data and methods.

Encapsulates may be thought of as "contains". Data also is referred to as attributes or properties. Methods are analogous to functions and also are referred to as behaviors. Every object has a special method called a constructor function (or simply, constructor), which is a function used to create an object.

JavaScript has many built-in objects, such as the Array, Image, Date, Window, and Document objects. A few common methods of the document object and the window object are illustrated below:

document.write("msg");
Writes a text string to a document
document.write("Hello World!")

Hello World!

window.alert("msg");
Displays an alert box with a message and an OK button
function disp_alert() {

alert("Hello again! This is how we" + '\n' + "add line breaks to an alert box!") }

window.prompt("msg","default");
Displays a dialog box prompting the user for input
function disp_prompt() { var name=prompt("Please enter your name","") if (name!=null && name!="") { document.write("Hello " + name + "! How are you today?") } }

window.confirm("msg");
Displays a dialog box with a message, a Cancel, and an OK button
function disp_confirm() { var name=confirm("Press a button") if (name==true) { document.write("You pressed the OK button!") } else { document.write("You pressed the Cancel button!") } }

window.open("URL", "name", "specs");


Opens a new browser window.
function open_win() { window.open("http://www.fsu.edu","new_window","toolbar=yes,location=yes,direct ories=no, status=no,menubar=yes,scrollbars=yes,resizable=no,width=400,height=400") }

CGS 3066: JavaScript Objects: String Object The String object is used to work with text.

Properties
Syntax: object.property_name Grayed properties are of lessor importance. Property constructor length Returns the number of characters in a string Description

Methods
Syntax: object.method_name() Grayed methods are of lessor importance. Method anchor("anchorname") big() blink() bold() charAt(index) charCodeAt(i) concat(string) fixed() fontcolor() fontsize() fromCharCode() Returns a string as an anchor Returns a string in big text Returns a string blinking Returns a string in bold Returns the character at a specified position Returns the Unicode of the character at a specified position Returns two concatenated strings Returns a string as teletype Returns a string in a specified color Returns a string in a specified size Returns the character value of a Unicode Description

indexOf(substring, index) Returns the position of the first occurrence of a specified string inside another string. Returns -1 if it never occurs italics() lastIndexOf(substring, index) link() match(strMatch) Returns a string in italic Returns the position of the first occurrence of a specified string inside another string. Returns -1 if it never occurs. Note: This method starts from the right and moves left! Returns a string as a hyperlink Similar to indexOf and lastIndexOf, but this method returns the specified string, or "null", instead of a numeric value

replace(strFind, strReplace) search(substring) slice(start, end)

Replaces the first instance of some specified characters with some new specified characters Returns an integer if the string contains some specified characters, if not it returns -1 Returns a string containing the portion of the string from index start through index end. If end is not specified, it returns from start through the end of the string. Returns a string as small text Splits a string into an array of strings . Delimiter acts as the character on which the string is divided. Returns a string strikethrough Returns a string as subscript Returns the specified characters. 14,7 returns 7 characters, from the 14th character Returns the specified characters. 7,14 returns all characters from the 7th up to but not including the 14th Returns a string as superscript Converts a string to lower case Converts a string to upper case

small() split(delimiter) strike() sub() substr(start, length) substring(start, end) sup() toLowerCase() toUpperCase()

CGS 3066: JavaScript Objects: Document Object The Document object is used to access all elements in a page. The Document object's collections, properties, methods, and events are described below:

Collections
Collection anchors[] applets[] attributes[] childNodes[] embeds[] forms[] images[] links[] plugins[] styleSheets[] Returns a reference to all Stylesheet objects in the document Returns a reference to all embedded objects in the document Returns a reference to all Form objects in the document Returns a reference to all Image objects in the document Returns a reference to all Link objects in the document Description Returns a reference to all Anchor objects in the document Returns a reference to all Applet objects in the document

Properties
Syntax: document.property_name Grayed properties are of lessor importance. Property alinkColor bgColor body cookie documentElement domain fgColor lastModified linkColor Description Sets or returns the color of the active links in the document Sets or returns the background-color of the document Specifies the beginning and end of the document body Sets or returns all cookies associated with the document Returns a reference to the root node of the document Returns the document server's domain name Sets or returns the text-color of the document Returns the date and time the document was last modified Sets or returns the color of the links in the document

referrer title URL vlinkColor

Returns the URL of the document that loaded the current document Returns the title of the document (text inside the HTML title element) Returns the URL of the current document Sets or returns the color of the visited links in the document

Methods
Syntax: document.method_name() Grayed methods are of lessor importance. Method clear() close() createAttribute("name") createElement("tag") createTextNode("txt") focus() getElementById("id") getElementsByName("name") getElementsByTagName("tag") open("mimetype"[,replace]) Description Clears all elements in the document Closes the output stream and displays the sent data Creates an attribute with a specified name Creates an element Creates a text string Gives the document focus Returns a reference to the first object with the specified ID Returns a collection of objects with the specified NAME Returns a collection of objects with the specified TAGNAME Opens a document for writing. If a document exists in the target it will be cleared. If this method has no arguments, a new window with about:blank is displayed Writes a text string to a document opened by open() Writes a text string followed by a new line character to a document opened by open()

write("str") writeln("str")

Events
Syntax: document.event_name="someJavaScriptCode" Grayed events are of lessor importance. Event onClick onDblClick onFocus Description Executes some code when a Click event occurs Executes some code when a Doubleclick event occurs Executes some code when a Focus event occurs

onKeyDown onKeyPress onKeyUp onMouseDown onMouseMove onMouseOut onMouseOver onMouseUp onResize

Executes some code when a Keydown event occurs Executes some code when a Keypress event occurs Executes some code when a Keyup event occurs Executes some code when a Mousedown event occurs Executes some code when a Mousemove event occurs Executes some code when a Mouseout event occurs Executes some code when a Mouseover event occurs Executes some code when a Mouseup event occurs Executes some code when a Resize event occurs

CGS 3066: JavaScript Objects: Form Object The Form object is used to access all forms in a page. The Form object's collections, properties, methods, and events are described below:

Objects
Syntax: objForm.object Grayed objects are of lessor importance. Object button Description An GUI pushbutton control. Methods are click(), blur(), and focus(). Properties: name - The name of the button type - The object's type. In this case, "button". value - The string displayed on the button. checkbox An GUI check box control. Methods are click(), blur(), and focus(). Properties: checked - Indicates whether the checkbox is checked. This is a read or write value. defaultChecked - Indicates whether the checkbox is checked by default. This is a read only value. name - The name of the checkbox. type - Type is "checkbox". value - A read or write string that specifies the value returned when the checkbox is selected.

FileUpload

This is created with the INPUT type="file". This is the same as the text element with the addition of a directory browser. Methods are blur(), and focus(). Properties: name - The name of the FileUpload object. type - Type is "file". value - The string entered which is returned when the form is submitted

hidden

An object that represents a hidden form field and is used for client/server communications. No methods exist for this object. Properties: name - The name of the Hidden object. type - Type is "hidden". value - A read or write string that is sent to the server when the form is submitted.

password

A text field used to send sensitive data to the server. Methods are blur(), focus(), and select(). Properties: defaultValue - The default value. name - The name of the password object." type - Type is "password". value - A read or write string that is sent to the server when the form is submitted.

radio

A GUI radio button control. Methods are click(), blur(), and focus(). Properties: checked - Indicates whether the radio button is checked. This is a read or write value. defaultChecked - Indicates whether the radio button is checked by default. This is a read only value. length - The number of radio buttons in a group. name - The name of the radio button. type - Type is "radio". value - A read or write string that specifies the value returned when the radio button is selected.

reset

Properties: name - The name of the reset object. type - Type is "reset". value - The text that appears on the button. By default it is "reset". A GUI selection list. This is basically a drop down list. Methods are blur(), and focus(). Properties: length - The number of elements contained in the options array. name - The name of the selection list. options - An array each of which identifies an options that may be selected in the list. selectedIndex - Specifies the current selected option within the select list type - Type is "select".

select

submit

A submit button object. Methods are click(), blur(), and focus(). Properties: name - The name of the submit button. type - Type is "submit". value - The text that will appear on the button.

text

A GUI text field object. Methods are blur(), focus(), and select(). Properties: defaultValue - The text default value of the text field. name - The name of the text field. type - Type is "text". value - The text that is entered and appears in the text field. It is sent to the server when the form is submitted.

textarea

A GUI text area field object. Methods are blur(), focus(), and select(). Properties: defaultValue - The text default value of the text area field. name - The name of the text area. type - Type is textarea.

value- The text that is entered and appears in the text area field. It is sent to the server when the form is submitted.

Properties
Syntax: objForm.property_name Grayed properties are of lessor importance. Property action Description This specifies the URL and CGI script file name the form is to be submitted to. It allows reading or changing the ACTION attribute of the HTML FORM tag. An array of fields and elements in the form. This is a read or write string. It specifies the encoding method the form data is encoded in before being submitted to the server. It corresponds to the ENCTYPE attribute of the FORM tag. The default is "application/x-www-form-urlencoded". Other encoding includes text/plain or multipart/form-data. The number of fields in the elements array. I.E. the length of the elements array. This is a read or write string. It has the value "GET" or "POST". The form name. Corresponds to the FORM Name attribute. The name of the frame or window the form submission response is sent to by the server. Corresponds to the FORM TARGET attribute.

elements encoding

length method name target

Methods
Syntax: objForm.method_name() Grayed methods are of lessor importance. Method reset() submit() Description Used to reset the form elements to their default values. Submits the form as though the submit button were pressed by the user.

Events
Syntax: objForm.event_name="someJavaScriptCode" Grayed events are of lessor importance.

Event onreset onsubmit

Description Executes some code when a Reset event occurs Executes some code when a Submit event occurs

CGS 3066: JavaScript Form Validation

Philosophy
JavaScript is commonly used to validate information inputted into forms thereby ensuring that information has been entered into required fields and, also, to ensure that the information is plausible (i.e., that an e-mail address includes an "@" symbol or that a phone number does not contain alpha characters [a-z or A-Z]). Note that form validation can be quite tricky. When writing your validation code, put yourself in the user's shoes. Consider what information might they, legitimately, want to input. A great frustration for any user is toseeminglyinput valid information into a form and subsequently be told that it is not valid. Consider a form that collects personal information such as your zip code, such as in the form below. First Name:

State:

Zip Code:

Country:

A logical first step may be to make the zip code field required and a second step may be to require that only numbers are accepted. However, doing so would be be overly restrictive. Although U.S. postal codes are composed primarily of numbers, a person may choose to enter their fully-defined 9 digit zip code, which would then contain a hyphen, such as 32308-1409. To accommodate this, you may revise your validation code so that it allows only numbers and the hyphen. However, again, this is likely to be overly restrictive as international postal codes often contain letters. To accommodate, you modify your code so that if the country field is U.S. then only numbers and hyphens are accepted but if the country is not the U.S., then numbers, letters, and hyphens are accepted.

Is this sufficient to ensure that a properly-formed zip code is entered?


No, it is not. For example, "125" would be accepted by the validation code that is outlined above. To accommodate, you may revise the validation code so the U.S. postal codes must be 5 digits, followed by an optional hyphen, and then followed by 4 digits (these 4 digits appear only if a hyphen has been entered). Under these guidelines, 32308-1409 and 32308 would be accepted, but 32-308 and 323081409 would not. However, the story is still not over. For example, not all 5 digit numbers are valid postal codes andif you collect the user's statethe zip code should correspond to a zip code within the given state. If the validation code were modified to account for these conditions, would the code be fail-proof? Likely not. It is very difficult to address all situations that may arise and that should not be your goal. Your goal should be to incorporate validation code that accounts for common situations. In general, validation code which is so restrictive that it ensures, beyond all doubt, that the information entered by the user is of a given format will do more harm than as it may frustrate users.

Validation Techniques
View, as a text file, a collection of functions that may be used for validation purposes. View sample forms and their validation code.

Form 1 Form 2 Form 3

Typically, the information within a form is validatedby a functionthat is called when the form is submitted.
<form action="script.pl" method="get" onsubmit="return validate(this);"> <p> Username: <input type="text" name="user" /> <input type="submit" value="Submit" /> </p> </form>
Submit

Username:

Note that the form tag, above, has an attribute that we have not yet seen - the onsubmit attribute. "onsubmit" is an example of an event handler; event handlers will be discussed in greater detail within the DHTML lectures. In brief, an event handler is used to react to an event caused by the user (i.e., when the user submits a form, clicks on a link, loads a page).
onsubmit="return validate(this);"

Looking at the onsubmit event handler one piece at a time:

onsubmitthe event handler itself, which returns the value of the validate function to the browser. The validate function returns a boolean value. If the function, and therefore the event handler, returns true then the form is passed to its action page. However, if false is returned, then the browser will cancel the passing of the form to the action page. returnthe return keyword acts as you might suspect - it returns a value. The values it can return can be of any data type, and can be defined by custom statements or by core objects. The return keyword is most often used within functions and within event handlers. If the return keyword is used in a function body, a value is returned (or sent) back to where function is called. If the return keyword is used in an event handler, a value is returned (or sent) to the browser. validate(this)a call to the validate function, which passes this as an argument thisJavaScript provides a special keyword, "this", which is a reference to the object that contains a JavaScript statement or function call. In this case, the keyword "this" passes a reference to the form to the function "validate". In other words, the information contained in the form is made available to the function.

<script language="JavaScript" type="text/javascript"> <!-function validate( appForm ) { if (appForm.user.value == "") { missinginfo ="_____________________________\n" + "You failed to correctly fill in your:\n\n

user name" +

"\n_____________________________" + "\nPlease re-enter and submit again!"; window.alert(missinginfo); return false; } else } //--> </script> return true;

CGS 3066: JavaScript Form Validation (continued) The discussion thus far has been to validate an entire form once it has been submitted. In many cases, the form needs to be validated - or at least adjusted - as the user inputs the information. Examples:

when the user clicks inside the Name input box, which gives it focus, the phrase "Enter name here" is deleted automatically. This saves the user from having to do so. when the user selects more than 2 checkboxes, the user is alerted that they may not do so. when the user indicates that, Yes, they have special dietary needs, the Dietary Needs textarea is automatically given focus to encourage the user to elaborate. when the user indicates that, No, they do not have special dietary needs, any text within the Dietary Needs textarea is deleted. when the inputs information into the Dietary Needs textarea, the Yes radio button is automatically checked.

Note: much of this code relies on use of the keyword 'this'. In particular, it relies on 'this.form'; 'this.form' refers to the parent form of the current element. I.e., specifying

<input type="text" name="textBox" onfocus="checkForm(this.form);"> passes the contents on the entire form in which the input box is contained. Name:
Enter name here

1. For what platform would you like more information? Choose no more than 2. Windows NT Windows 2000 Windows XP Linux Unix 2. Do you have special dietary needs? Yes | No

Dietary needs:

Submit Form

Reset Form

<script type="text/javascript"> <!-//function prevents user from selecting more than 2 platforms function checkCount(theForm) { var count = 0; for(i=0;i<theForm.platform.length;i++) { if (theForm.platform[i].checked == true) { count += 1; if (count > 2) { theForm.platform[i].checked = false; alert("Note that you may check only 2 of the platform types."); } } } }

//--> </script> <form action="thankyou.asp" method="post" id="form1" name="form1" onsubmit="return validate(this);"> <p><b> Name:</b> <input name="fname" value="Enter name here" size="25" maxlength="30" onfocus="this.value='';"/> &nbsp;&nbsp;</p> <ol> <li><b>For what platform would you like more information? </b> Choose no more than 2.<br /> <input type="checkbox" value="Windows NT" name="platform" onclick="checkCount(this.form);"/> Windows NT<br /> <input type="checkbox" value="Windows 2000" name="platform" onclick="checkCount(this.form);"/> Windows 2000<br /> <input type="checkbox" value="Windows XP" name="platform" onclick="checkCount(this.form);"/> Windows XP<br /> <input type="checkbox" value="Linux" name="platform" onclick="checkCount(this.form);"/> Linux<br /> <input type="checkbox" value="Unix" name="platform" onclick="checkCount(this.form);"/> Unix <br /> <br /> </li> <li><b>Do you have special dietary needs?<br /> <input name="diet" type="radio" value="yes" onclick="this.form.dietNeeds.focus();"/> Yes | <input name="diet" type="radio" value="no" onclick="this.form.dietNeeds.value = '';"/> No<br /> <br /> Dietary needs:</b><br /> <textarea name="dietNeeds" rows="4" cols="40" onfocus="this.form.diet[0].checked = true"></textarea> <br /> </li> </ol> <p> &nbsp;&nbsp;&nbsp; <input type="submit" value="Submit Form" name="submit" class="button" /> &nbsp;&nbsp;&nbsp; <input type="reset" value="Reset Form" name="reset" class="button" /> </p>

</form>

GS 3066: JavaScript Objects: Window Object The Window object corresponds to the browser window. A Window object is created automatically with every instance of a <body> or <frameset> tag. A selection of the Window object's collections, objects, properties, methods, and events are described below. Syntax to refer to a window.

Collections
Collection frames[] Description Returns all named frames in the window

Objects

Object document event history location navigator screen

Description Represents the HTML document object in the window. Represents the state of an event Contains the URLs visited from the window. Contains the current URL of the window. Contains information about the browser. Contains information about the client's screen.

Properties
Syntax: window.property_name Property closed defaultStatus dialogHeight dialogLeft dialogTop dialogWidth length name opener parent returnValue screenLeft screenTop self status top Description Returns a Boolean value that specifies whether the referenced window has been closed Sets or returns the default text in the statusbar of the windows (will be displayed when the page loads) Sets or returns the height of the modal dialog window Sets or returns the left coordinates of the modal dialog window Sets or returns the top coordinates of the modal dialog window Sets or returns the width of the modal dialog window Sets or returns the number of frames in the window Sets or returns the name of the window Sets or returns a reference to the window that created the window Returns the parent window Sets or returns the value returned from the modal dialog window Returns the x-coordinate of the upper left corner of the browser relative to the upper left corner of the screen Returns the y-coordinate of the top corner of the browser relative to the top corner of the screen Returns a reference to the current window Sets or returns the text in the status bar of the window Returns the topmost ancestor window

Methods

Syntax: window.method_name() Method alert("msg") blur() clearInterval(ID) clearTimeout(ID) close() confirm("msg") focus() moveBy(x,y) moveTo(x,y) Description Displays an alert box with a message and an OK button Removes focus from the current window Cancels a timeout that is set with the setInterval() method Cancels a timeout that is set with the setTimeout() method Closes the current window Displays a dialog box with a message, a Cancel, and an OK button Sets focus on the current window Moves the window a specified number of pixels in relation to its current co-ordinates Moves the window's left and top edge to the specified coordinates

open(["URL", "name", "specs", Opens a new browser window. The arguments can take the replace]) following values: "URL" - Optional. Specifies the URL of the page to display if no URL is specified, a new window with about:blank is displayed) "name" - Optional. Specifies the value for the target attribute on a form or a link. The following values are supported: _blank URL is loaded into a new window _media URL is loaded into the content area of the Media Bar (IE6+) _parent URL is loaded into the parent frame _search URL is opened in the browser's search pane (IE5+) _self _top URL replaces the current page URL replaces any framesets that may be loaded

"specs" - Optional. A comma-separated list of items. The following values are supported: channelmode = yes | no | 1 | 0 whether to display the window in theater mode. Default is no

directories = yes | whether to add directory buttons. Default is no | 1 | 0 yes

fullscreen = yes | whether to display the browser in full-screen no | 1 | 0 mode. Default is no. A window in full-screen mode must also be in theater mode height = number the height of the window, in pixels. Min. value is 100 left = number location = yes | no | 1 | 0 menubar = yes | no | 1 | 0 the left position, in pixels whether to display the address field. Default is yes whether to display the menu bar. Default is yes

resizable = yes | whether the window is resizable. Default is no | 1 | 0 yes scrollbars = yes | whether to display scroll bars. Default is yes no | 1 | 0 status = yes | no | whether to add a status bar. Default is yes 1|0 titlebar = yes | no whether to display the title bar. Ignored |1|0 unless the calling application is an HTML Application or a trusted dialog box. Default is yes toolbar = yes | no whether to display the browser toolbar. |1|0 Default is yes top = number width = number width = number the top position, in pixels the width of the window, in pixels. Min. value is 100 the width of the window, in pixels. Min. value is 100

replace - Optional. Specifies whether the URL creates a new entry or replaces the current entry in the history list. The following values are supported: true URL replaces the current document in the history list false URL creates a new entry in the history list print() prompt(["msg", "default"]) Prints the contents of the current window Displays a dialog box prompting the user for input. The arguments can take the following values: msg Optional. The message to display in the dialog box.

Default is "" default Optional. The default text in the input field resizeBy(x,y) resizeTo(width, height) scrollBy(x,y) Resizes the window by the specified pixels. Note: This method does not work on dialog windows Resizes the window to the specified width and height. Note: This method does not work on dialog windows Scrolls the content by the specified number of pixels. Note: The visible property of the window's scrollbar must be set to true if using this method Scrolls the content to the specified co-ordinates Calls a function / evaluate an expression every time a specified interval (in milliseconds) has been reached. The arguments can take the following values: code Required. A pointer to a function or the code to be executed Optional. JScript | VBScript | JavaScript

scrollTo(x,y) setInterval(code, millisec[, "lang"])

millisec Required. The number of milliseconds lang setTimeout(code, millisec[, "lang"]) Calls a function / evaluate an expression after a specified number of milliseconds. The arguments can take the following values: code Required. A pointer to a function or the code to be executed Optional. JScript | VBScript | JavaScript

millisec Required. The number of milliseconds lang

* The default unit of measure for dialogHeight and dialogWidth in IE4 is em; in IE5 it is px. Other values to use: cm, mm, in, pt, pc, or ex. For consistent results, use px! Note: The min. dialogHeight you can specify is 100px.

Events
Syntax: window.event_name="someJavaScriptCode" Event onBlur onError onFocus onLoad Description Executes some code when a Blur event occurs Executes some code when an Error event occurs Executes some code when a Focus event occurs Executes some code when an Load event occurs

onResize onUnload

Executes some code when a Resize event occurs Executes some code when an Unload event occurs

You might also like