tybca- 302 unit – 1 javascriptjavascript introduction javascript is the most popular scripting...

230
1 TYBCA- 302 UNIT – 1 JAVASCRIPT

Upload: others

Post on 11-Jun-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

1

TYBCA- 302

UNIT – 1

JAVASCRIPT

Page 2: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

2

JavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari. What is JavaScript? JavaScript was designed to add interactivity to HTML pages. JavaScript is a scripting language. A scripting language is a lightweight programming language. JavaScript is usually embedded directly into HTML pages. JavaScript is an interpreted language. (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license. Are Java and JavaScript the same? NO! Java and JavaScript are two completely different languages in both concept and design!Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++. What can a JavaScript do? JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document. write("<h1>" + name + "</h1>") can write a variable text into an HTML page JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer The Real Name is ECMAScript JavaScript's official name is ECMAScript.ECMAScript is developed and maintained by the ECMA organization. ECMA-262 is the official JavaScript standard. The language was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in all Netscape and Microsoft browsers since 1996.

Page 3: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

3

The development of ECMA-262 started in 1996, and the first edition of was adopted by the ECMA General Assembly in June 1997.The standard was approved as an international ISO (ISO/IEC 16262) standard in 1998. The development of the standard is still in progress. JavaScript How To The HTML <script> tag is used to insert a JavaScript into an HTML page. Put a JavaScript into an HTML page

The example below shows how to use JavaScript to write text on a web page:Example <html> <body> <scripttype="text/javascript"> document.write("HelloWorld!"); </script> </body> </html>

The example below shows how to add HTML tags to the JavaScript:

Example

<html> <body> <script type="text/javascript"> document.write("<h1>Hello World!</h1>"); </script> </body> </html>

Example Explained To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the type attribute to define the scripting language. So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and ends: <html> <body> <script type="text/javascript"> ... </script> </body> </html> The document.write command is a standard JavaScript command for writing output to a page.By entering the document.write command between the <script> and </script> tags,

Page 4: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

4

the browser will recognize it as a JavaScript command and execute the code line. In this case the browser will write Hello World! to the page: <html> <body> <script type="text/javascript"> document.write("Hello World!"); </script> </body> </html> How to Handle Simple Browsers Browsers that do not support JavaScript, will display JavaScript as page content.To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should be used to "hide" the JavaScript.Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment) after the last JavaScript statement, like this: <html> <body> <script type="text/javascript"> <!-- document.write("Hello World!"); //--> </script> </body> </html> The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag. JavaScript Where To JavaScripts can be put in the body and in the head sections of an HTML page. Where to Put the JavaScript JavaScripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, or at a later event, such as when a user clicks a button. When this is the case we put the script inside a function. Scripts in <head> Scripts to be executed when they are called, or when an event is triggered, are placed in functions.Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.

Example <html> <head> <script type="text/javascript"> function message()

Page 5: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

5

{ alert("This alert box was called with the onload event"); } </script> </head> <body onload="message()"> </body> </html>

Scripts in <body> If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.

Example <html> <head> </head> <body> <script type="text/javascript"> document.write("This message is written by JavaScript"); </script> </body> </html>

Scripts in <head> and <body> You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section.

Example <html> <head> <script type="text/javascript"> function message() { alert("This alert box was called with the onload event"); } </script> </head> <body onload="message()">

Page 6: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

6

<script type="text/javascript"> document.write("This message is written by JavaScript"); </script> </body> </html>

Using an External JavaScript If you want to run the same JavaScript on several pages, without having to write the same script on every page, you can write a JavaScript in an external file.Save the external JavaScript file with a .js file extension. Note: The external script cannot contain the <script></script> tags! To use the external script, point to the .js file in the "src" attribute of the <script> tag:

Example <html> <head> <script type="text/javascript" src="xxx.js"></script> </head> <body> </body> </html>

JavaScript Statements JavaScript is a sequence of statements to be executed by the browser. JavaScript is Case Sensitive Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely when you write JavaScript statements, create or call variables, objects and functions. JavaScript Statements A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser what to do. This JavaScript statement tells the browser to write "Hello Dolly" to the web page: document.write("Hello Dolly"); It is normal to add a semicolon at the end of each executable statement. Most people think this is a good programming practice, and most often you will see this in JavaScript examples on the web.The semicolon is optional (according to the JavaScript standard), and the browser is supposed to interpret the end of the line as the end of the statement. Because of this you will often see examples without the semicolon at the end. Note: Using semicolons makes it possible to write multiple statements on one line.

Page 7: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

7

JavaScript Code JavaScript code (or just JavaScript) is a sequence of JavaScript statements. Each statement is executed by the browser in the sequence they are written.This example will write a heading and two paragraphs to a web page:

Example <script type="text/javascript"> document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); </script>

JavaScript Blocks JavaScript statements can be grouped together in blocks.Blocks start with a left curly bracket {, and ends with a right curly bracket }.The purpose of a block is to make the sequence of statements execute together. This example will write a heading and two paragraphs to a web page:

Example <script type="text/javascript"> { document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); } </script>

The example above is not very useful. It just demonstrates the use of a block. Normally a block is used to group statements together in a function or in a condition (where a group of statements should be executed if a condition is met).

<script type="text/javascript"> /* document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); */ </script>

Using Comments at the End of a Line In the following example the comment is placed at the end of a code line:

Page 8: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

8

Example <script type="text/javascript"> document.write("Hello"); // Write "Hello" document.write(" Dolly!"); // Write " Dolly!" </script>

Data Types in JavaScript: JavaScript uses four data types-numbers; strings, boolean values, and a null value-to represent all the information the language can handle. Compared with most languages, this is a small number of data types, but it is sufficient to intelligently handle most data used in everything except the most complex programs. In JavaScript, there are three primary data types, two composite data types, and two special data types. Primary Data Types The primary (primitive) data types are:

• String • Number • Boolean

Composite Data Types The composite (reference) data types are:

• Object • Array

Special Data Types The special data types are:

• Null • Undefined

Literals The term literals refers to the way in which each of the four data types are represented. Literals are fixed values which literally provide a value in a program. For example, 11 is a literal number, "hello" is a string literal, and true is a boolean literal.You have already seen literals in use in the previous chapters when you gave arguments to different

Page 9: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

9

methods in the form of text strings such as "Welcome to Netscape Navigator 2.0!" and "Enter Your Name:". For each data type, there are different ways of specifying literals. Numbers The JavaScript number type encompasses what would be several types in languages such as Java. Using the numbers, it is possible to express both integers and floating point values. Integers Integers are numbers without any portion following the decimal point; that is, they are whole numbers-no fractions. Integers can be either positive or negative numbers. The maximum integer size is dependent on the platform running the JavaScript application. In JavaScript, you can express integers in three different bases: base 10 (decimal-what you normally use in everyday situations), base 8 (known as octal), and base 16 (hexadecimal).

NOTE Base 8 numbers can have digits only up to 7, so a decimal value of 18 would be an octal value of 22. Similarly, hexadecimal allows digits up to F, where A is equivalent to decimal 10 and F is 15. So, a decimal value of 18 would be 12 in hexadecimal notation.

In order to distinguish between these three bases, JavaScript uses the notations outlined in Table x.1 to specify the different bases. Table x.1 Specifying bases in JavaScript.

Number System Notation

Decimal (base 10) A normal integer without a leading 0 (zero) (e.g., 752)

Octal (base 8) An integer with a leading 0 (zero) (e.g., 056)

Hexadecimal (base 16) An integer with a leading 0x or 0X (e.g., 0x5F or 0XC72)

Floating Point Values Floating point values can include a fractional component. A floating point literal includes a decimal integer plus either a decimal point and a fraction expressed as another decimal number or an exponent indicator and a type suffix, as shown in the following examples: 7.2945 34.2 2E3 Floating point literals must, at a minimum, include a decimal integer and either the decimal point or the exponent indicator ("e" or "E"). As with integers, floating point values can be positive or negative.

NOTE It should be noted that JavaScript's handling of floating point numbers can introduce inaccuracy into some calculations. You should keep this

Page 10: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

10

in mind for your programs. Strings You have already encountered string literals in "Your First Script," where you used them as arguments for several methods. Technically, a string literal contains zero or more characters enclosed, as you know, in single or double quotes: "Hello!" '245' ""

The last example is called the empty string. It is important to note that the empty string is distinct from the null value in JavaScript.

NOTE Strings are different from other data types in JavaScript. Strings are actually objects .

Boolean A boolean literal can take two values: either true or false. This type of literal comes in handy when comparing data and making decisions, as you will see later in this chapter.

NOTE Unlike Java, C, and other languages, in JavaScript boolean values can only be represented with true and false. Values of 1 and 0 are not considered boolean values in JavaScript.

The null Data Type The null value is a special value in JavaScript. The null value represents just that-nothing. If you try to reference a variable that isn't defined and therefore has no value, the value returned is the null value. Likewise, in a prompt dialog box, if the user selects the Cancel button, a null value is returned. This is distinct from a value of zero or an empty string where this is an actual value. The null value is indicated in JavaScript by the term null. The undefined Data Type The undefined value is returned when you use an object property that does not exist, or a variable that has been declared, but has never had a value assigned to it.

Page 11: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

11

you can check to see if a variable exists by comparing it to undefined, although you can check if its type is undefinedby comparing the type of the variable to the string "undefined". The following example shows how to find out the variable x has been declared: var x; // This method works. if (x == undefined) { document.write("comparing x to undefined <br/>"); } // This method doesn't work - you must check for the string "undefined". if (typeof(x) == undefined) { document.write("comparing the type of x to undefined <br/>"); } // This method does work. if (typeof(x) == "undefined") { document.write("comparing the type of x to the string 'undefined'"); } // Output: // comparing x to undefined // comparing the type of x to the string 'undefined' You can also compare the undefined value to null. This comparison is true if the property someObject.prop is null or if the property someObject.prop does not exist. someObject.prop == null; To find out whether an object property exists, you can use the in operator: if ("prop" in someObject) NaN In addition to these values, some functions return a special value called NaN-which means that the value is not a number. parseInt() and parseFloat() on UNIX systems are an example of functions which returns NaNwhen the argument passed to them cannot be evaluated to a number. Values can be tested to see if they are NaN by using the isNaN() function which returns true or false based on the nature of the argument passed to the function. Composite Data Types

Page 12: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

12

Casting JavaScript is what is called a loosely typed programming language. In loosely typed languages, the type of a literal or variable (which we discuss in the next section) is not defined when a variable is created and can, at times, change based on the context. By comparison, Java and C are not loosely typed. In its earliest forms, LiveScript and JavaScript allowed programmers to combine two literals of different types, with the result being a literal value of the same type as the first literal in the expression. For instance, combining the string "Count to " with the integer literal 10 results in a string with the value "Count to 10". By contrast, adding together the numeric literal 3.5 and the string "10" results in the floating point numeric literal 13.5.

This process is known as casting. The first example casts the number 10 into a string, and the second casts the string 10 into a number.

However, as JavaScript and Java have been brought closer together, this has begun to change. In the version of JavaScript currently available, it is no longer possible to cast a string into a number by using a form such as 0 + "1". JavaScript has added the parseInt() and parseFloat() functions, which convert strings into integers or floating point numbers. For instance, parseInt("13") returns the integer 13 andparseFloat("45.2") returns the floating point number 45.2. It is still possible to cast a number into a string as in "Count to " + 10 evaluating to a string with the value "Count to 10". JavaScript Variables Variables are "containers" for storing information. JavaScript variables are used to hold values or expressions. A variable can have a short name, like x, or a more descriptive name, like carname.Rules for JavaScript variable names: Variable names are case sensitive (y and Y are two different variables) Variable names must begin with a letter or the underscore character Example A variable's value can change during the execution of a script. You can refer to a variable by its name to display or change its value. Declaring (Creating) JavaScript Variables Creating variables in JavaScript is most often referred to as "declaring" variables. You can declare JavaScript variables with the var statement: var x; var carname; After the declaration shown above, the variables are empty (they have no values yet). However, you can also assign values to the variables when you declare them: var x=5;

Page 13: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

13

var carname="Volvo"; After the execution of the statements above, the variable x will hold the value 5, and carname will hold the value Volvo. Note: When you assign a text value to a variable, use quotes around the value. Assigning Values to Undeclared JavaScript Variables If you assign values to variables that have not yet been declared, the variables will automatically be declared. These statements: x=5; carname="Volvo"; have the same effect as: var x=5; var carname="Volvo"; Redeclaring JavaScript Variables If you redeclare a JavaScript variable, it will not lose its original value. var x=5; var x; After the execution of the statements above, the variable x will still have the value of 5. The value of x is not reset (or cleared) when you redeclare it. JavaScript Arithmetic As with algebra, you can do arithmetic operations with JavaScript variables: y=x-5; z=y+5; JavaScript Operators Arithmetic Operators

Operator Description Examples + (add) Adds numeric operands or concatenates strings. In

the case of mixed numeric and string operands, the numeric result will always be converted to a string value just before being concatenated to the string operand, yielding a string output. For example: var output=24+"5" //result is "245" var output2=24+1+"5" //result is "255" var output3=1+"5"+24 //result is "1524"

1) x+y 2) "Me"+" You" Result: "Me You"

- (subtract) Subtracts numeric operands. If one of the operands is a string, JavaScript will try to convert it to a number first (ie: "5" becomes 5), or if unsuccessful, NaN is returned for the expression.

x-7 20-10 //returns 10

Page 14: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

14

20-'10' //returns 10 20-'what' //returns NaN

* (multiply) Multiplies numeric operands. If one of the operands is a string, JavaScript will try to convert it to a number first (ie: "5" becomes 5), or if unsuccessful, NaN is returned for the expression.

5*2

/ (divide) Divides numeric operands. If one of the operands is a string, JavaScript will try to convert it to a number first (ie: "5" becomes 5), or if unsuccessful, NaN is returned for the expression. Dividing by 0 yields the value NaN (Not a Number)

y/x

% (modulo) Returns the remainder when the first operand is divided by the second operand. If one of the operands is a string, JavaScript will try to convert it to a number first (ie: "5" becomes 5), or if unsuccessful, NaN is returned for the expression. The modulo operator is useful to determine whether a number is odd or even, for example: var scores=[3,34,12,53,23,82] document.write(scores.join(", ")+"<br />") for (var i=0; i<scores.length; i++){ if (scores[i]%2==1) //odd number? document.write("<b>odd, </b>") else document.write("<b>even, </b>") } Output:

7%2 //returns 1

++ (increment) Increments the operand by 1. Note the following two possible behaviours: 1) Pre increment: If operator is used before operand (ie: ++x), it increments the operand and evaluates to the incremented value. 2) Post increment: If operator is used following operand (ie: x++), it increments the operand but evaluates to the unincremented value.

Using x=2 for each example below: 1) x++ Result: x=3 2) y= ++x Result: 3 3) y= x++ Result: y=2

-- decrement Decrements the operand by 1. Note the following two possible behaviours: 1) Pre decrement: If operator is used before operand

x--

Page 15: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

15

(ie: --x), it increments the operand and evaluates to the incremented value. 2) Post decrement: If operator is used following operand (ie: x--), it increments the operand but evaluates to the unincremented value.

Unary minus (-) Used in front of a lone operand to make it negative. If operand isn't a number, JavaScript will try to convert it first (NaN is returned if unsuccessful). The operand itself is not altered.

y=-x Result: y equals -x x remains x

Unary plus (+) Does nothing other than explicitly specifies an operand's implied positive sign. However, if operand isn't a number, JavaScript will try to convert it first (NaN is returned if unsuccessful).

y=+x Result: y equals x x remains x

JavaScript Assignment Operators Assignment operators are used to assign values to JavaScript variables. Given that x=10 and y=5, the table below explains the assignment operators: Operator Example Same As Result = x=y x=5 += x+=y x=x+y x=15 -= x-=y x=x-y x=5 *= x*=y x=x*y x=50 /= x/=y x=x/y x=2 %= x%=y x=x%y x=0 The + Operator Used on Strings The + operator can also be used to add string variables or text values together. To add two or more string variables together, use the + operator. txt1="What a very"; txt2="nice day"; txt3=txt1+txt2; After the execution of the statements above, the variable txt3 contains "What a verynice day". To add a space between the two strings, insert a space into one of the strings: txt1="What a very "; txt2="nice day"; txt3=txt1+txt2; or insert a space into the expression:

Page 16: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

16

txt1="What a very"; txt2="nice day"; txt3=txt1+" "+txt2; After the execution of the statements above, the variable txt3 contains: "What a very nice day" Adding Strings and Numbers The rule is: If you add a number and a string, the result will be a string!

Example x=5+5; document.write(x); x="5"+"5"; document.write(x); x=5+"5"; document.write(x); x="5"+5; document.write(x);

JavaScript Comparison and Logical Operators Comparison and Logical operators are used to test for true or false. Comparison Operators Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x=5, the table below explains the comparison operators: Operator Description Example == is equal to x==8 is false === is exactly equal to (value and type) x===5 is true

x==="5" is false != is not equal x!=8 is true > is greater than x>8 is false < is less than x<8 is true >= is greater than or equal to x>=8 is false <= is less than or equal to x<=8 is true

Page 17: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

17

How Can it be Used Comparison operators can be used in conditional statements to compare values and take action depending on the result: if (age<18) document.write("Too young"); You will learn more about the use of conditional statements in the next chapter of this tutorial. Logical Operators Logical operators are used to determine the logic between variables or values.Given that x=6 and y=3, the table below explains the logical operators: Operator Description Example && and (x < 10 && y > 1) is true || or (x==5 || y==5) is false ! not !(x==y) is true Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax variablename=(condition)?value1:value2 Example greeting=(visitor=="PRES")?"Dear President ":"Dear "; If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value "Dear President " else it will be assigned "Dear". Javascript Bit-Wise Operator:

Operator Description & Bitwise AND. | Bitwise OR ^ Bitwise XOR. ~ Bitwise NOT << Shift left. >> Shift right. >>> Shift right, zero fill.

Example- Bitwise Operator

Page 18: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

18

This example uses the Bitwise Operator Shift Left to shift the value 2 to the left four bits (binary 10 to binary 1000), resulting in 8: var test=2; test=test<<2 alert(test) //alerts 8 Other Operators:

Operator Description (,) comma Primarily used in a for loop when you wish to insert multiple expressions

for the test conditions, the comma (,) operator evaluates its left and right operands, and returnss the value of the right. for (var i=0, y=0; i<5; i++, y+=2){ document.write(i+" "+y+"<br />") } Output:

?: The Conditional Operator (?:) is a shorthand method for returning the

result of either exp1 or exp2, depending on whether condition evaluates to true or false. If true, the value of exp1 is returned, or if false, the value of exp2 instead. (condition)? exp1 : exp2 For example: y=-1 x=(y<0)? 5: 10 //x contains 5 Mor example(s).

delete Deletes a variable defined not using "var", custom object property, method, or array element. It returns true if successful, false if not. For example: var myarray=['joe', 'mary', 'jane'] var boss={name: 'george'} worker={name: 'peter'} var x=3 y=4 delete myarray[1] //returns true, myarray[1] now undefined delete boss //returns false, since boss is a declared variable delete worker //returns true, since worker is an undeclared variable delete x //returns false, since x is a declared variable delete y //returns true, since y is an undeclared variable

in The "in" operator takes an object or array as its right operand, and a string denoting the property you wish to search for as its left operand. Returns true if property exists in object, false if not. var myarray=['joe', 'mary', 'jane']

Page 19: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

19

var workers={worker1: 'peter', worker2: 'edward', worker3: 'john'} "lastModified" in document //true, document.lastModified exists "length" in myarray //true "mary" in myarray //false, "mary" is an array value, not property (use array.indexOf() instead) "worker1" in workers //true Note that properties deleted using the "delete" operator above will return false when tested for using "in".

instanceof Returns a Boolean value indicating whether the left hand operand is of the object type specified in the right hand operand. Here object type refers to the name of the object you wish to test for, such as Date, String, Array etc. Use instanceof as a more clear-cut way of detecting the type of an object or variable versus typeof. For example: var today=new Date() alert(today instanceof Date) //alerts true, today is a Date object var mycars=["Honda", "Toyota", "Ford" alert(mycars instanceof Array) //alerts true, mycars is an Array object function house(w, h){ this.area=w*h } var myhouse=new house(100, 200) alert(myhouse instanceof house) //alerts true

new Creates a new instance of a custom or select built-in JavaScript objects such as Date. Only objects with a constructor function can be instantialized using the "new" operator. The "this" keyword can then be used anywhere inside the function to refer to the object or object instance. var today=new Date() //create new instance of Date object function triangle(base, height){ this.area=base*height/2 } var bigtriangle=new triangle(200, 150) //create new instance of triangle object

try/catch/finally Allows you to intercept exception (aka runtime) errors in JavaScript and handle them as you see fit. Examples of exceptions include trying to reference an undefined variable, or calling a non existent JavaScript method. It does not catch syntax errors (ie: forgetting to end a string with a quotation mark). The typical set up involves a try and catch clause to catch a possible exception, and react accordingly if caught: try{ somefunction() alert('I guess you do exist')

Page 20: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

20

} catch(e){ alert('An error has occurred: '+e.message) } In the above, if "somefunction()" doesn't exist, the browser immediately skips the reminder of what's inside try() and executes the code inside catch(). There's another clause, finally, that if defined will be executed regardless of whether an error occurs in the try clause: try{ undefinedfunction() alert('I guess you do exist') } catch(e){ alert('An error has occurred: '+e.message) } finally{ alert('I am alerted regardless of the outcome above') } try should never be defined just by itself, but always followed by either catch, finally, or both. Within each clause, you can define additional try/catch/finally statements following the same aforementioned rule (nesting). Take the instance where an error has occurred within the catch clause- defining an additional try/catch statement inside it takes care of it: var ajaxrequest=null if (window.ActiveXObject){ //Test for support for different versions of ActiveXObject in IE try { ajaxrequest=new ActiveXObject("Msxml2.XMLHTTP") } catch (e){ try{ ajaxrequest=new ActiveXObject("Microsoft.XMLHTTP") } //end inner try catch (e){ alert("I give up. Your IE doesn't support Ajax!") } //end inner catch } //end outer catch } else if (window.XMLHttpRequest) // if Mozilla, Safari etc ajaxrequest=new XMLHttpRequest() ajaxrequest.open('GET', 'process.php', true) //do something with request Here I'm using a nested try/catch statement to try and determine in IE which version of the ActiveX Object it supports that's needed to initialize an Ajax request. Using object detection won't work here, since the issue

Page 21: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

21

isn't whether the browser supports ActiveXObject here, but which version. More info: "Handling runtime errors in JavaScript using try/catch/finally".

typeof The "typeof" operator allows you to probe the data type of its operand, such as whether a variable is string, numeric, or even undefined. Here are some of the possible return values: Evaluates to Indicates

"number" Operand is a number. Example: typeof 0 //number

"string" Operand is a string.

"boolean" Operand is a Boolean. Examples: typeof false //boolean

"object"

Operand is an object. Note that apart from most core and user defined objects, arrays and null itself also evaluates to "object" in typeof. Examples: typeof window //object typeof Math //object typeof new Array() //object typeof null //object

"function"

Operand is a function. JavaScript core methods, custom functions, and even some core objects return "function" as their type. Examples: typeof alert//function (window.alert()) typeof Date //function typeof new Function("var x=3") //function typeof document.getElementById //function

null Operand is null.

"undefined"

Operand is not defined. Undefined properties or non existent variables all return "undefined" as their type. The following tests whether a variable exists, by checking if its data type is "undefined": if (typeof x=="undefined") alert("x doesn't exist!")

void Evaluates a lone operand without returning a value. Most commonly used to define JavaScript links, where the link executes a JavaScript code instead of its default action when clicked on. For example: <a href="javascript:void(window.open('http://google.com'))">Open Google</a>

Operator precedence and associativity

Page 22: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

22

Operator precedence refers to the order in which operators are evaluated when more than one type is used in an expression. The higher an operator's precedence, the earlier it is evaluated next to operators with lower precedence. For example: a+b*c=20 The above expression is evaluated in the order of the multiplication operators (*) first, then plus operator (+), and finally, the assignment operator (=), due to their respective precedence order in JavaScript. Precedence can be manually overridden using a parenthesis. The expression (a+b)*c=20 with its parenthesis around the plus operator alters the precedence so the addition is evaluated first. Operator associativity refers to the order in which operators with the same precedence are evaluated when they appear alongside one another. There is "left to right" and "right to left" associativity. Consider this example: a+b-c=5 Here b is first added to a then the result subtracted by c, in that order. Below lists the precedence (1=highest precedence, 15=lowest) and associativity order of all operators in JavaScript: Operator precedence and associativity chart

Operator Precedence Associativity . (dot property reference) [] (bracket property reference) new ()

1 Left to right

++ --

2 Right to left

+ (unary +, NOT the addition sign) - (unary negate -, NOT subtract sign) ~ (bitwise not) ! (not) delete typeof void

3 Right to left

* / % + (addition) - (subtraction)

4 Left to right

<< >> >>>

5 Left to right

< <= >

6 Left to right

Page 23: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

23

>= instanceof in & 7 Left to right ^ 8 Left to right | 9 Left to right && 10 Left to right || 11 Left to right ?: 12 Right to left = 13 Right to left *= /= %= += -= <<== >>== >>>= &= ^= |=

14 Right to left

, (comma) 15 Left to right String escape sequences Escape sequences allow you to parse string literals in JavaScript for special characters/ formatting, such as newlines within a TEXTATEA's input. Below lists these escape sequences:

Properties Description \b Backspace. \f Form feed. \n Newline. \O Nul character. \r Carriage return. \t Horizontal tab. \v Vertical tab. \' Single quote or apostrophe. \" Double quote.

Page 24: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

24

\\ Backslash. \ddd The Latin-1 character specified by the three octal digits between 0

and 377. ie, copyright symbol is \251. \xdd The Latin-1 character specified by the two hexadecimal digits dd

between 00 and FF. ie, copyright symbol is \xA9. \udddd The Unicode character specified by the four hexadecimal digits

dddd. ie, copyright symbol is \u00A9. Examples Adding newlines (line breaks) when alerting text alert("Welcome to JavaScript Kit\nEnjoy your stay!") Adding quotes within a string var myquote="George said \"Life is like a box of chocolates\"" JavaScript Reserved Words The following are reserved words in JavaScript. They cannot be used as JavaScript variables, functions, methods, loop labels, or object names. Reserved Words

abstract boolean break byte case catch char class const continue debugger default delete do double

else enum export extends false final finally float for function goto if implements import in

instanceof int interface long native new null package private protected public return short static super

switch synchronized this throw throws transient true try typeof var void volatile while with

DECISION MAKING - Conditional Checking JavaScript If...Else Statements Conditional statements are used to perform different actions based on different conditions. Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript we have the following conditional statements:

Page 25: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

25

if statement - use this statement to execute some code only if a specified condition is true if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false if...else if....else statement - use this statement to select one of many blocks of code to be executed switch statement - use this statement to select one of many blocks of code to be executed If Statement Use the if statement to execute some code only if a specified condition is true. Syntax if (condition) { code to be executed if condition is true }

Example <script type="text/javascript"> //Write a "Good morning" greeting if //the time is less than 10 var d=new Date(); var time=d.getHours(); if (time<10) { document.write("<b>Good morning</b>"); } </script>

Notice that there is no ..else.. in this syntax. You tell the browser to execute some code only if the specified condition is true. If...else Statement Use the if....else statement to execute some code if a condition is true and another code if the condition is not true. Syntax if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true }

Page 26: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

26

Example <script type="text/javascript"> //If the time is less than 10, you will get a "Good morning" greeting. //Otherwise you will get a "Good day" greeting. var d = new Date(); var time = d.getHours(); if (time < 10) { document.write("Good morning!"); } else { document.write("Good day!"); } </script>

If...else if...else Statement Use the if....else if...else statement to select one of several blocks of code to be executed. Syntax if (condition1) { code to be executed if condition1 is true } else if (condition2) { code to be executed if condition2 is true } else { code to be executed if condition1 and condition2 are not true }

Example <script type="text/javascript"> var d = new Date() var time = d.getHours()

Page 27: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

27

if (time<10) { document.write("<b>Good morning</b>"); } else if (time>10 && time<16) { document.write("<b>Good day</b>"); } else { document.write("<b>Hello World!</b>"); } </script>

JavaScript Switch Statement Conditional statements are used to perform different actions based on different conditions. The JavaScript Switch Statement Use the switch statement to select one of many blocks of code to be executed. Syntax switch(n) { case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 } This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.

Example <script type="text/javascript">

Page 28: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

28

//You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date(); theDay=d.getDay(); switch (theDay) { case 5: document.write("Finally Friday"); break; case 6: document.write("Super Saturday"); break; case 0: document.write("Sleepy Sunday"); break; default: document.write("I'm looking forward to this weekend!"); } </script>

JavaScript Popup Boxes JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box. Alert Box An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed. JavaScript alerts are ideal for the following situations: If you want to be absolutely sure they see a message before doing anything on the website. You would like to warn the user about something. For example "the following page contains humor not suitable for those under the age of 14." An error has occurred and you want to inform the user of the problem. When asking users for confirmation of some action. For example, if they have just agreed to sign over the deed to their house and you want to ask them again if they are absolutely positive they want to go through with this decision! Syntax

alert("sometext");

Page 29: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

29

Example <html> <head> <script type="text/javascript"> function show_alert() { alert("I am an alert box!"); } </script> </head> <body> <input type="button" onclick="show_alert()" value="Show alert box" /> </body> </html>

Confirm Box A confirm box is often used if you want the user to verify or accept something.When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. Confirmation are most often used to confirm an important actions that are taking place on a website. For example, they may be used to confirm an order submission or notify visitors that a link they clicked will take them to another website. Syntax confirm("sometext");

Example <html> <head> <script type="text/javascript"> function show_confirm() { var r=confirm("Press a button"); if (r==true) { alert("You pressed OK!");

Page 30: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

30

} else { alert("You pressed Cancel!"); } } </script> </head> <body> <input type="button" onclick="show_confirm()" value="Show confirm box" /> </body> </html>

Prompt Box A prompt box is often used if you want the user to input a value before entering a page.When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null. Syntax prompt("sometext","defaultvalue");

Example <html> <head> <script type="text/javascript"> function show_prompt() { var name=prompt("Please enter your name","Harry Potter"); if (name!=null && name!="") { document.write("Hello " + name + "! How are you today?"); } } </script> </head> <body>

Page 31: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

31

<input type="button" onclick="show_prompt()" value="Show prompt box" /> </body> </html>

JavaScript Arrays: Arrays are one way of keeping a program more organized. They allow you to do some things that are difficult without them. Arrays are usually a group of the same variable type that use an index number to distinguish them from each other. Three Ways to Declare an Array in JavaScript You can declare JavaScript arrays: by using the array constructor, the literal notation, or by calling methods with array return types. JavaScript Array Constructor We can explicitly declare an array with the JavaScript "new" keyword to instantiate the array in memory (i.e. create it, and make it available). // Declare an array (using the array constructor) var arlene1 = new Array(); var arlene2 = new Array("First element", "Second", "Last"); We first declared an empty array. We then assigned three elements to the second array, while declaring it. "new Array()" is the array constructor. Array Literal Notation Below, we use an alternate method to declaring arrays: // Declare an array (using literal notation) var arlene1 = []; var arlene2 = ["First element", "Second", "Last"]; We declared above the exact same arrays as previously; instead of new Array(?), you can use square brackets, optionally enclosing elements. Using square brackets (vs. array constructor) is called the "array literal notation." Implicit Array Declaration JavaScript also lets you create arrays indirectly, by calling specific methods:

Page 32: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

32

// Create an array from a method's return value var carter = "I-learn-JavaScript"; var arlene3 = carter.split("-"); We indirectly created an array by using the string split() method; several other JavaScript methods return an array as result. As illustration, the array returned by the split() method is identical to the one declared below. var arlene4 = new Array("I", "learn", "JavaScript"); Assigning Size When Declaring Arrays The same way we initialized array elements while declaring the array, JavaScript also lets you directly assign a size while declaring the array: // Declare array of size 7 var arlene = new Array(7); The script above sets the array size (or "length") during the declaration. This property will be explained in our array length tutorial. Initialize new arrays as you declare them To avoid script errors, you should get into the habit of initializing an array when you declare it: by default, JavaScript will assign the special value of NULL to any variable you declare without initializing it with a value. In the case of array variables, you can either set the values of the array when you declare it (that assumes that you already know which values the array will contain - not always the case), or declare the array and initialize it as an empty array: // Declare an empty array using literal notation: var arlene = []; // The variable now contains an array of length zero Another way to declare an empty JavaScript array: // Use the "new" constructor to declare an array: var arlene = new Array(); // Array variable has been created (contains no element) An "empty array" is just a regular array: the only difference is that it contains zero elements. To check if a JavaScript array is empty or not, simply check if its length property (the array size) is equal to zero or not. Declaring a Multidimensional Array in JavaScript When we showed you how to declare one-dimensional arrays, we covered three declaration methods. All three can be used with multidimensional arrays; this tutorial only mentions the literal notation and array constructor. Using the Literal Notation The same syntax is used to declare multidimensional arrays: we simply "nest" the declaration, as shown below. // Declare a multidimensional array (literal notation) var arlene = [ ["A1","A2"], ["B1","B2"], ["C1","C2"] ]; In the JavaScript code above, we created a 3x2 multidimensional array; if it were represented as a table, the array would look like this:

Page 33: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

33

A1 A2 B1 B2 C1 C2 Using the Array Constructor There is another, more explicit way to declare multidimensional arrays in JavaScript, by creating arrays inside arrays: // Declare a standard, one-dimensional array var arlene = new Array(); // Declare arlene's first and second element as arrays arlene[0] = new Array(); arlene[1] = new Array("I", "learn", "JavaScript"); Referencing One-dimensional Array Elements To reference standard array elements, simply use the array variable name, followed by the numerical index of the element enclosed in square brackets. // Declare a one-dimensional JavaScript array var arlene = new Array("I", "learn", "JavaScript"); alert( arlene[2] ); The script above creates an array, and assigns it three string elements. The last line of our script sends the third array element (at index 2) to the alert() method, and produces the result: Referencing Multidimensional Array Elements Referencing elements in multidimensional arrays works much the same way; you only have to remember that the leftmost index points to the outermost array. // Declare a multidimensional array of 2x3 dimension var arlene = [ ["A1","A2"], ["B1","B2"], ["C1","C2"] ]; alert( arlene[0][0] +" ... "+ arlene[0][1] ); The alert() method in the script above calls the first and second element of the first array element (read it once more, slowly). Here is the result: To display the first and second element of the second "inner array", use the following script: // Re-using the multidimensional array we declared earlier... alert( arlene[1][0] +" ... "+ arlene[1][1] ); The alert returns what would correspond to the second row in a tabular representation of our array: Associative Arrays in javascript Create an Associative Array in JavaScript

Page 34: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

34

In the script below, we create the basis for a Acronym Lookup program in JavaScript. We will use an associative array to reference the meaning of each acronym, and use the acronym as the associative array's index: // Declare a regular JavaScript array var arlene = new Array(); // Now make it an asssociative array arlene["CSS" ] = "Cascading Style Sheets"; arlene["HTML"] = "HyperText Markup Language"; arlene["W3C" ] = "World Wide Web Consortium"; // Get the meaning of the "CSS" acronym alert( arlene["CSS"] ); The final line of JavaScript code produces the result: Associative Arrays and JavaScript Object Properties Associative arrays in JavaScript are equivalent to declaring object properties on the fly (rather, properties of object instances, if you do not use the prototype property.) Conversely, values of built-in object properties can be called as associative array elements. var arlene = new Array("first", "second", "last"); // Retrieve the array length as an associative array element: alert( arlene["length"] ); The script above treats the built-in Array object's length property as an associative array element. The actual array dimension was returned: The reverse holds true: the script below declares an associative array element, and then retrieves its value as an instance property, using "dot notation". var arlene = new Array(); // Declare an associative array element: arlene["CSS"] = "Cascading Style Sheets"; // Retrieve the value using dot notation: alert( arlene.CSS ); Predictably, our script returned the same result as the associative array notation used earlier, using the arlene["CSS"] syntax. Associative arrays are tightly related to the ability JavaScript offers to create properties on-the-fly for objects or instances of objects. JavaScript Functions A function will be executed by an event or by a call to the function. JavaScript Functions To keep the browser from executing a script when the page loads, you can put your script into a function. A function contains code that will be executed by an event or by a call to the function.

Page 35: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

35

You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file). Functions can be defined both in the <head> and in the <body> section of a document. However, to assure that a function is read/loaded by the browser before it is called, it could be wise to put functions in the <head> section. How to Define a Function Syntax function functionname(var1,var2,...,varX) { some code } The parameters var1, var2, etc. are variables or values passed into the function. The { and the } defines the start and end of the function. Note: A function with no parameters must include the parentheses () after the function name. Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name. JavaScript Function Example

Example <html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello World!"); } </script> </head> <body> <form> <input type="button" value="Click me!" onclick="displaymessage()" /> </form> </body> </html>

If the line: alert("Hello world!!") in the example above had not been put within a function, it would have been executed as soon as the line was loaded. Now, the script is not executed before a user hits the input button. The function displaymessage() will be executed if the input button is clicked. The return Statement

Page 36: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

36

The return statement is used to specify the value that is returned from the function.So, functions that are going to return a value must use the return statement.The example below returns the product of two numbers (a and b):

Example <html> <head> <script type="text/javascript"> function product(a,b) { return a*b; } </script> </head> <body> <script type="text/javascript"> document.write(product(4,3)); </script> </body> </html>

The Lifetime of JavaScript Variables If you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.

Page 37: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

37

JavaScript predefined functions This page discusses JavaScript predefined functions such as escape, unescape, eval, isNaN, tostring, alert, and others. Conversion and Comparison escape(string) - Encodes a string from ASCII into an ISO Latin-1 (ISO 8859-1) character set which is suitable for HTML processing. It is passed the string to be encoded, and returns the encoded string. unescape - Converts an ISO8859-1 character set to ASCII. If a string is "My phone # is 123-456-7890", after the escape function, it is "My%20phone%20%23%20is%20123-456-7890". After unescape, it is "My phone # is 123-456-7890". eval()- Converts a string to integer or float value. It can also evaluate expressions included with a string. In the example, value1 becomes 62. value1 = eval("124/2") , isNaN(value) - If the value passed is a not a number, the boolean value of true is returned, if it is a number, it returns false. if (isNaN(string1)) { document.write("String1 is not a number\n"); } else { document.write(String1 is a number\n"); } parseFloat() - Returns floating point numbers the same as the parseInt function, but looks for floating point qualified strings and returns their value as a float. The first line below returns a value of 123, and the second line returns 9.683. value1 = parseFloat("123") value2 = parseFloat("9.683") parseInt()- Converts a string to an integer returning the first integer encountered which is contained in the string. In the example, value1 becomes 12. value1 = parseInt("12b13") , If no integer value were found such as in the string "abcd", then a value of 0 is returned.

Methods that belong to all objects toString() - Converts an object to a string. The syntax is shown below. Radix is the base value for the conversion, which may be 10 for decimal conversion. The value 1 is used for binary conversion, and 8 is used for octal conversion. object.tostring(radix) Dialog Boxes alert(message) - Displays an alert box with a message defined by the string message. Example: alert("An error occurred!")

Page 38: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

38

confirm(message) - When called, it will display the message and two boxes. One box is "OK" and the other is "Cancel". If OK is selected, a value of true is returned, otherwise a value of false is returned. An example: if (confirm("Select OK to continue, Cancel to abort")) { document.write("Continuing") } else { document.write("Operation Canceled") } prompt(message) - Displays a box with the message passed to the function displayed. The user can then enter text in the prompt field, and choose OK or Cancel. If the user chooses Cancel, a NULL value is returned. If the user chooses OK, the string value entered in the field is returned. An example: var response=prompt("Enter your name") if (response != null) { document.write(response) }

Page 39: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

39

LOOPING: JavaScript For Loop Loops execute a block of code a specified number of times, or while a specified condition is true. JavaScript Loops Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this. In JavaScript, there are two different kind of loops: for - loops through a block of code a specified number of times while - loops through a block of code while a specified condition is true The for Loop The for loop is used when you know in advance how many times the script should run. Syntax for (var=startvalue;var<=endvalue;var=var+increment) { code to be executed } Example The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs. Note: The increment parameter could also be negative, and the <= could be any comparing statement.

Example <html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=5;i++) { document.write("The number is " + i); document.write("<br />"); } </script> </body> </html>

Page 40: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

40

The while loop Loops execute a block of code a specified number of times, or while a specified condition is true. The while Loop The while loop loops through a block of code while a specified condition is true. Syntax while (var<=endvalue) { code to be executed } Note: The <= could be any comparing statement. Example The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:

Example <html> <body> <script type="text/javascript"> var i=0; while (i<=5) { document.write("The number is " + i); document.write("<br />"); i++; } </script> </body> </html>

The do...while Loop The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true. Syntax do { code to be executed } while (var<=endvalue);

Page 41: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

41

Example The example below uses a do...while loop. The do...while loop will always be executed at least once, even if the condition is false, because the statements are executed before the condition is tested:

Example <html> <body> <script type="text/javascript"> var i=0; do { document.write("The number is " + i); document.write("<br />"); i++; } while (i<=5); </script> </body> </html>

JavaScript Break and Continue Statements The break Statement The break statement will break the loop and continue executing the code that follows after the loop (if any).

Example <html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=10;i++) { if (i==3) { break; } document.write("The number is " + i); document.write("<br />"); } </script> </body>

Page 42: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

42

</html>

The continue Statement The continue statement will break the current loop and continue with the next value.

Example <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { if (i==3) { continue; } document.write("The number is " + i); document.write("<br />"); } </script> </body> </html>

JavaScript For...In Statement The for...in statement loops through the elements of an array or through the properties of an object. Syntax for (variable in object) { code to be executed } Note: The code in the body of the for...in loop is executed once for each element/property. Note: The variable argument can be a named variable, an array element, or a property of an object. Example Use the for...in statement to loop through an array:

Example

Page 43: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

43

<html> <body> <script type="text/javascript"> var x; var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; mycars[2] = "BMW"; for (x in mycars) { document.write(mycars[x] + "<br />"); } </script> </body> </html>

JavaScript Events Events are actions that can be detected by JavaScript. By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags. Examples of events: A mouse click A web page or an image loading Mousing over a hot spot on the web page Selecting an input field in an HTML form Submitting an HTML form A keystroke Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs! onLoad and onUnload The on Load and onUnload events are triggered when the user enters or leaves the page.

Page 44: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

44

The onLoad event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!". onFocus, onBlur and onChange The onFocus, onBlur and onChange events are often used in combination with validation of form fields. Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field: <input type="text" size="30" id="email" onchange="checkEmail()"> onSubmit The onSubmit event is used to validate ALL form fields before submitting it. Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled: <form method="post" action="xxx.htm" onsubmit="return checkForm()"> onMouseOver and onMouseOut onMouseOver and onMouseOut are often used to create "animated" buttons. Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected: <a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false"><img src="w3s.gif" alt="W3Schools" /></a> Image onabort Event The onabort event occurs when loading of an image is aborted. Syntax onabort="JavaScriptCode" Parameter Description JavaScriptCode Required. Specifies a JavaScript to be executed when the event occurs Example Call a function if loading of an image is aborted: <html> <head> <script type="text/javascript">

Page 45: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

45

function abortImage() { alert('Error: Loading of the image was aborted!') } </script> </head> <body> <img src="image_w3default.gif" onabort="abortImage()" /> </body> </html> onblur Event The onblur event occurs when an object loses focus. Syntax onblur="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event

occurs. Supported by the following HTML tags: <a>, <acronym>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <button>, <caption>, <cite>, <dd>, <del>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <frame>, <frameset>, <h1> to <h6>, <hr>, <i>, <iframe>, <img>, <input>, <ins>, <kbd>, <label>, <legend>, <li>, <object>, <ol>, <p>, <pre>, <q>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var> Supported by the following JavaScript objects: button, checkbox, fileUpload, layer, frame, password, radio, reset, submit, text, textarea, window Example In this example we will execute some JavaScript code when a user leaves an input field: <html> <head> <script type="text/javascript"> function upperCase() { var x=document.getElementById("fname").value document.getElementById("fname").value=x.toUpperCase() } </script> </head> <body> Enter your name: <input type="text" id="fname" onblur="upperCase()">

Page 46: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

46

</body> </html> onblur Event The onblur event occurs when an object loses focus. Syntax onblur="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event

occurs. Supported by the following HTML tags: <a>, <acronym>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <button>, <caption>, <cite>, <dd>, <del>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <frame>, <frameset>, <h1> to <h6>, <hr>, <i>, <iframe>, <img>, <input>, <ins>, <kbd>, <label>, <legend>, <li>, <object>, <ol>, <p>, <pre>, <q>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var> Supported by the following JavaScript objects: button, checkbox, fileUpload, layer, frame, password, radio, reset, submit, text, textarea, window Example In this example we will execute some JavaScript code when a user leaves an input field: <html> <head> <script type="text/javascript"> function upperCase() { var x=document.getElementById("fname").value document.getElementById("fname").value=x.toUpperCase() } </script> </head> <body> Enter your name: <input type="text" id="fname" onblur="upperCase()"> </body> </html> onclick Event The onclick event occurs when an object gets clicked. Syntax

Page 47: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

47

onclick="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event

occurs. Supported by the following HTML tags: <a>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <cite>, <code>, <dd>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <h1> to <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <map>, <object>, <ol>, <p>, <pre>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var> Supported by the following JavaScript objects: button, document, checkbox, link, radio, reset, submit Example In this example the text in the first input field will be copied to the second input field when a button is clicked: <html> <body> Field1: <input type="text" id="field1" value="Hello World!"> <br /> Field2: <input type="text" id="field2"> <br /><br /> Click the button below to copy the content of Field1 to Field2. <br /> <button onclick="document.getElementById('field2').value= document.getElementById('field1').value">Copy Text</button> </body> </html> ondblclick Event The ondblclick event occurs when an object gets double-clicked. Syntax ondblclick="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event

occurs. Supported by the following HTML tags: <a>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <cite>, <code>, <dd>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <h1> to <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <map>, <object>, <ol>, <p>, <pre>, <samp>, <select>, <small>, <span>, <strong>, <sub>,

Page 48: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

48

<sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var> Supported by the following JavaScript objects: document, link Example In this example the second field changes according to the first field when you double-click on the button: <html> <body> Field1: <input type="text" id="field1" value="Hello World!"> <br /> Field2: <input type="text" id="field2"> <br /><br /> Click the button below to copy the content of Field1 to Field2. <br /> <button ondblclick="document.getElementById('field2').value= document.getElementById('field1').value">Copy Text</button> </body> </html> onerror Event The onerror event is triggered when an error occurs loading a document or an image. Syntax onerror="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event

occurs. Supported by the following HTML tags: <img>, <object>, <style> Supported by the following JavaScript objects: window, image Example In this example an alert box will be displayed if an error occurs when loading an image: <img src="image.gif" onerror="alert('The image could not be loaded.')"> onfocus Event The onfocus event occurs when an object gets focus. Syntax onfocus="SomeJavaScriptCode" Parameter Description

Page 49: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

49

SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event occurs.

Supported by the following HTML tags: <a>, <acronym>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <button>, <caption>, <cite>, <dd>, <del>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <frame>, <frameset>, <h1> to <h6>, <hr>, <i>, <iframe>, <img>, <input>, <ins>, <kbd>, <label>, <legend>, <li>, <object>, <ol>, <p>, <pre>, <q>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var> Supported by the following JavaScript objects: button, checkbox, fileUpload, layer, frame, password, radio, reset, select, submit, text, textarea, window Example In this example the background color of the input fields change when they get focus: <html> <head> <script type="text/javascript"> function setStyle(x) { document.getElementById(x).style.background="yellow" } </script> </head> <body> First name: <input type="text" onfocus="setStyle(this.id)" id="fname"> <br /> Last name: <input type="text" onfocus="setStyle(this.id)" id="lname"> </body> </html> onkeydown Event The onkeydown event occurs when a keyboard key is pressed. Syntax onkeydown="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event

occurs. Supported by the following HTML tags: <a>, <acronym>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <cite>, <code>, <dd>, <del>, <dfn>, <div>, <dt>, <em>,

Page 50: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

50

<fieldset>, <form>, <h1> to <h6>, <hr>, <i>, <input>, <kbd>, <label>, <legend>, <li>, <map>, <object>, <ol>, <p>, <pre>, <q>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var> Supported by the following JavaScript objects: document, image, link, textarea Example In this example the user cannot type numbers into the input field: <html> <body> <script type="text/javascript"> function noNumbers(e) { var keynum var keychar var numcheck if(window.event) // IE { keynum = e.keyCode } else if(e.which) // Netscape/Firefox/Opera { keynum = e.which } keychar = String.fromCharCode(keynum) numcheck = /\d/ return !numcheck.test(keychar) } </script> <form> <input type="text" onkeydown="return noNumbers(event)" /> </form> </body> </html> onkeypress Event The onkeypress event occurs when a keyboard key is pressed or held down. Syntax onkeypress="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event

Page 51: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

51

occurs. Supported by the following HTML tags: <a>, <acronym>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <cite>, <code>, <dd>, <del>, <dfn>, <div>, <dt>, <em>, <fieldset>, <form>, <h1> to <h6>, <hr>, <i>, <input>, <kbd>, <label>, <legend>, <li>, <map>, <object>, <ol>, <p>, <pre>, <q>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var> Supported by the following JavaScript objects: document, image, link, textarea Example In this example the user cannot type numbers into the input field: <html> <body> <script type="text/javascript"> function noNumbers(e) { var keynum var keychar var numcheck if(window.event) // IE { keynum = e.keyCode } else if(e.which) // Netscape/Firefox/Opera { keynum = e.which } keychar = String.fromCharCode(keynum) numcheck = /\d/ return !numcheck.test(keychar) } </script> <form> <input type="text" onkeypress="return noNumbers(event)" /> </form> </body> </html> onKeyUp Event The onkeyup event occurs when a keyboard key is released. Syntax onkeyup="SomeJavaScriptCode"

Page 52: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

52

Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event

occurs. Supported by the following HTML tags: <a>, <acronym>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <cite>, <code>, <dd>, <del>, <dfn>, <div>, <dt>, <em>, <fieldset>, <form>, <h1> to <h6>, <hr>, <i>, <input>, <kbd>, <label>, <legend>, <li>, <map>, <object>, <ol>, <p>, <pre>, <q>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var> Supported by the following JavaScript objects: document, image, link, textarea Example When typing letters in the input field in the following example, the letters will change to uppercase (one by one): <html> <head> <script type="text/javascript"> function upperCase(x) { var y=document.getElementById(x).value document.getElementById(x).value=y.toUpperCase() } </script> </head> <body> Enter your name: <input type="text" id="fname" onkeyup="upperCase(this.id)"> </body> </html> onload Event The onload event occurs immediately after a page or an image is loaded. Syntax onload="JavaScriptCode" Parameter Description JavaScriptCode Required. Specifies a JavaScript to be executed when the

event occurs Supported by the following HTML tags: <body>, <img> Supported by the following JavaScript objects: body, image

Page 53: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

53

Example 1 Alert "Page is loaded" immediately after a page is loaded: <html> <head> <script type="text/javascript"> function load() { alert("Page is loaded"); } </script> </head> <body onload="load()"> <h1>Hello World!</h1> </body> </html> Example 2 Alert "Image is loaded" immediately after an image is loaded: <html> <head> <script type="text/javascript"> function loadImage() { alert("Image is loaded"); } </script> </head> <body> <img src="w3javascript.gif" onload="loadImage()" /> </body> </html> onmousedown Event The onmousedown event occurs when a mouse button is clicked. Syntax onmousedown="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event

occurs. Supported by the following HTML tags: <a>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <cite>, <code>, <dd>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <h1> to <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <map>, <ol>,

Page 54: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

54

<p>, <pre>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var> Supported by the following JavaScript objects: button, document, link Example 1 In this example an alert box is displayed when clicking on the picture: <img src="image_w3default.gif" onmousedown="alert('You clicked the picture!')"> Example 2 In this example an alert box will alert the tag name of the element you clicked on: <html> <head> <script type="text/javascript"> function whichElement(e) { var targ if (!e) var e = window.event if (e.target) targ = e.target else if (e.srcElement) targ = e.srcElement if (targ.nodeType == 3) // defeat Safari bug targ = targ.parentNode var tname tname=targ.tagName alert("You clicked on a " + tname + " element.") } </script> </head> <body onmousedown="whichElement(event)"> <h2>This is a header</h2> <p>This is a paragraph</p> <img border="0" src="ball16.gif" alt="Ball"> </body> </html> onmousemove Event The onmousemove event occurs when the mouse pointer is moved. Syntax onmousemove="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the

event occurs.

Page 55: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

55

Supported by the following HTML tags: <a>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <cite>, <code>, <dd>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <h1> to <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <map>, <ol>, <p>, <pre>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var> Supported by the following JavaScript objects: onmousemove is, by default, not an event of any object, because mouse movement happens very frequently. Example In the following example we will display an alert box when the user moves the mouse pointer over the image: <img src="image_w3default.gif" alt="W3Schools" onmousemove="alert('Visit W3Schools!')" /> onmouseout Event The onmouseout event occurs when the mouse pointer moves away from a specified object. Syntax onmouseout="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the

event occurs. Supported by the following HTML tags: <a>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <cite>, <code>, <dd>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <h1> to <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <map>, <ol>, <p>, <pre>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var> Supported by the following JavaScript objects: layer, link Example 1 In the following example we will display an alert box when the user moves the mouse pointer over the image: <img src="image_w3default.gif" alt="W3Schools" onmouseout="alert('Visit W3Schools!')" /> Example 2 In the following example we will add an image that should act as a link button on a web page. We will then add an onMouseOver event and an onMouseOut event that will run two JavaScript functions that will change between two images: <html> <head> <script type="text/javascript"> function mouseOver() { document.getElementById("b1").src="b_blue.gif" }

Page 56: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

56

function mouseOut() { document.getElementById("b1").src="b_pink.gif" } </script> </head> <body> <a href="http://www.w3schools.com" target="_blank" onmouseover="mouseOver()" onmouseout="mouseOut()"> <img border="0" alt="Visit W3Schools!" src="b_pink.gif" id="b1" /></a> </body> </html> onmouseover Event The onmouseover event occurs when the mouse pointer moves over a specified object. Syntax onmouseover="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the

event occurs. Supported by the following HTML tags: <a>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <cite>, <code>, <dd>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <h1> to <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <map>, <ol>, <p>, <pre>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var> Supported by the following JavaScript objects: layer, link Example 1 In the following example we will display an alert box when the user moves the mouse pointer over the image: <img src="image_w3default.gif" alt="W3Schools" onmouseout="alert('Visit W3Schools!')" /> Example 2 In the following example we will add an image that should act as a link button on a web page. We will then add an onMouseOver event and an onMouseOut event that will run two JavaScript functions that will change between two images: <html> <head> <script type="text/javascript"> function mouseOver() {

Page 57: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

57

document.getElementById("b1").src ="b_blue.gif" } function mouseOut() { document.getElementById("b1").src ="b_pink.gif" } </script> </head> <body> <a href="http://www.w3schools.com" target="_blank" onmouseover="mouseOver()" onmouseout="mouseOut()"> <img border="0" alt="Visit W3Schools!" src="b_pink.gif" id="b1" /></a> </body> </html> onmouseup Event The onmouseup event occurs when a mouse button is released. Syntax onmouseup="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event

occurs. Supported by the following HTML tags: <a>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>, <caption>, <cite>, <code>, <dd>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <h1> to <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <map>, <ol>, <p>, <pre>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var> Supported by the following JavaScript objects: button, document, link Example 1 In this example an alert box is displayed when the mouse button is released after clicking the picture: <img src="image_w3default.gif" onmouseup="alert('You clicked the picture!')"> Example 2 In this example an alert box will alert the tag name of the element you clicked on: <html> <head> <script type="text/javascript"> function whichElement(e) {

Page 58: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

58

var targ if (!e) var e = window.event if (e.target) targ = e.target else if (e.srcElement) targ = e.srcElement if (targ.nodeType == 3) // defeat Safari bug targ = targ.parentNode var tname tname=targ.tagName alert("You clicked on a " + tname + " element.") } </script> </head> <body onmouseup="whichElement(event)"> <h2>This is a header</h2> <p>This is a paragraph</p> <img border="0" src="ball16.gif" alt="Ball"> </body> </html> Form onreset Event The onreset event occurs when the reset button in a form is clicked. Syntax onreset="JavaScriptCode" Parameter Description JavaScriptCode Required. Specifies a JavaScript to be executed when the

event occurs Example Display an alert box when the Reset button is clicked: <form onreset="alert('The form will be reset')"> Firstname: <input type="text" name="fname" value="Donald" /><br /> Lastname: <input type="text" name="lname" value="Duck" /><br /><br /> <input type="reset" value="Reset" /> </form> onselect Event The onselect event occurs when text is selected in a text or textarea field. Syntax onselect="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event

occurs.

Page 59: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

59

Supported by the following HTML tags: <input type="text">, <textarea> Supported by the following JavaScript objects: text, textarea Example In this example an alert box will be displayed if some of the text is selected: <form> Select text: <input type="text" value="Hello world!" onselect="alert('You have selected some of the text.')"> </form> onresize Event The onresize event occurs when a window or frame is resized. Syntax onresize="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event

occurs. Supported by the following HTML tags: <a>, <address>, <b>, <big>, <blockquote>, <body>, <button>, <cite>, <code>, <dd>, <dfn>, <div>, <dl>, <dt>, <em>, <fieldset>, <form>, <frame>, <h1> to <h6>, <hr>, <i>, <img>, <input>, <kbd>, <label>, <legend>, <li>, <object>, <ol>, <p>, <pre>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>, <textarea>, <tt>, <ul>, <var> Supported by the following JavaScript objects: window Example In this example an alert box would be displayed when a user tries to resize the window: <body onresize="alert('You have changed the size of the window')"> </body> onselect Event The onselect event occurs when text is selected in a text or textarea field. Syntax onselect="SomeJavaScriptCode" Parameter Description SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event

occurs. Supported by the following HTML tags: <input type="text">, <textarea>

Page 60: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

60

Supported by the following JavaScript objects: text, textarea Example In this example an alert box will be displayed if some of the text is selected: <form> Select text: <input type="text" value="Hello world!" onselect="alert('You have selected some of the text.')"> </form> Form onsubmit Event The onsubmit event occurs when the submit button in a form is clicked. Syntax onsubmit="JavaScriptCode" Parameter Description JavaScriptCode Required. Specifies a JavaScript to be executed when the

event occurs Example Display an alert box when the Submit button is clicked: <html> <head> <script type="text/javascript"> function greeting() { alert("Welcome " + document.forms["frm1"]["fname"].value + "!") } </script> </head> <body> What is your name?<br /> <form name="frm1" action="submit.htm" onsubmit="greeting()"> <input type="text" name="fname" /> <input type="submit" value="Submit" /> </form> </body> </html> onunload Event The onunload event occurs when a user exits a page. Syntax onunload="SomeJavaScriptCode" Parameter Description

Page 61: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

61

SomeJavaScriptCode Required. Specifies a JavaScript to be executed when the event occurs.

Supported by the following HTML tags: <body>, <frameset> Supported by the following JavaScript objects: window Example In this example an alert box will be displayed when the page is closed: <body onunload="alert('The onunload event was triggered')"> </body> JavaScript Events JavaScript Events are items that transpire based on an action. A document event is the loading of an HTML document. A form event is the clicking on a button. Events are objects with properties. Event Properties x -Mouse x coordinate when the event happened. y -Mouse y coordinate when the event happened. JavaScript defines five types of events which are form, image, image map, link, and window events. Events are associated with HTML tags. The definitions of the events described below are as follows: Form Events blur - The input focus was lost. change - An element lost the focus since it was changed. focus - The input focus was obtained. reset - The user reset the object, usually a form. select - Some text is selected submit - The user submitted an object, usually a form. Image Events abort - A user action caused an abort. error - An error occurred. load - The object was loaded. Image Map Events mouseOut - The mouse is moved from on top a link. mouseOver - The mouse is moved over a link. Link Events click - An object was clicked. mouseOut - The mouse is moved from on top a link.

Page 62: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

62

mouseOver - The mouse is moved over a link. Window Events blur - The input focus was lost. error - An error occurred. focus - The input focus was obtained. load - The object was loaded. unload - The object was exited.

Event Association Events are associated with HTML tags. The definitions of the events described below are as follows: abort - A user action caused an abort of an image or document load. blur - A frame set, document, or form object such as a text field loses the focus for input. click - Happens when a link or image map is clicked on change - Happens when a form field is changed by the user and it loses the focus. error - An error happened loading a image or document. focus - A frame set, document, or form object such as a text field gets the focus for input. load - The event happens when an image or HTML page has completed the load process in the browser. mouseOut - The event happens when the mouse is moved from on top of a link or image map mouseOver - The event happens when the mouse is placed on a link or image map. reset - The user reset the object which is usually a form. submit - The user submitted an object which is usually a form. unload - The object such as a framesed or HTML document was exited by the user.

Page 63: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

63

JavaScript Try...Catch Statement The try...catch statement allows you to test a block of code for errors. JavaScript - Catching Errors When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page. The try...catch Statement The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs. Syntax try { //Run some code here } catch(err) { //Handle errors here } Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error! Examples The example below is supposed to alert "Welcome guest!" when the button is clicked. However, there's a typo in the message() function. alert() is misspelled as adddlert(). A JavaScript error occurs. The catch block catches the error and executes a custom code to handle it. The code displays a custom error message informing the user what happened:

Example <html> <head> <script type="text/javascript"> var txt=""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.\n\n";

Page 64: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

64

txt+="Error description: " + err.description + "\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); } } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html>

The next example uses a confirm box to display a custom message telling users they can click OK to continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false, the user clicked Cancel, and the code redirects the user. If the confirm method returns true, the code does nothing:

Example <html> <head> <script type="text/javascript"> var txt=""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.\n\n"; txt+="Click OK to continue viewing this page,\n"; txt+="or Cancel to return to the home page.\n\n"; if(!confirm(txt)) { document.location.href="http://www.w3schools.com/"; } } } </script> </head>

Page 65: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

65

<body> <input type="button" value="View message" onclick="message()" /> </body> </html>

The throw Statement The throw statement can be used together with the try...catch statement, to create an exception for the error. Learn about the throw statement in the next chapter. JavaScript Throw Statement The throw statement allows you to create an exception. The Throw Statement The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages. Syntax throw(exception) The exception can be a string, integer, Boolean or an object. Note that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error! Example The example below determines the value of a variable called x. If the value of x is higher than 10, lower than 0, or not a number, we are going to throw an error. The error is then caught by the catch argument and the proper error message is displayed:

Example <html> <body> <script type="text/javascript"> var x=prompt("Enter a number between 0 and 10:",""); try { if(x>10) { throw "Err1"; } else if(x<0) { throw "Err2"; }

Page 66: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

66

else if(isNaN(x)) { throw "Err3"; } } catch(er) { if(er=="Err1") { alert("Error! The value is too high"); } if(er=="Err2") { alert("Error! The value is too low"); } if(er=="Err3") { alert("Error! The value is not a number"); } } </script> </body> </html>

JavaScript Special Characters In JavaScript you can add special characters to a text string by using the backslash sign. Insert Special Characters The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string. Look at the following JavaScript code: var txt="We are the so-called "Vikings" from the north."; document.write(txt); In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called To solve this problem, you must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal: var txt="We are the so-called \"Vikings\" from the north."; document.write(txt); JavaScript will now output the proper text string: We are the so-called "Vikings" from the north.

Page 67: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

67

Here is another example: document.write ("You \& I are singing!"); The example above will produce the following output: You & I are singing! The table below lists other special characters that can be added to a text string with the backslash sign: Code Outputs \' single quote \" double quote \& ampersand \\ backslash \n new line \r carriage return \t tab \b backspace \f form feed JavaScript Guidelines Some other important things to know when scripting with JavaScript. JavaScript is Case Sensitive A function named "myfunction" is not the same as "myFunction" and a variable named "myVar" is not the same as "myvar". JavaScript is case sensitive - therefore watch your capitalization closely when you create or call variables, objects and functions. White Space JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The following lines are equivalent: name="Hege"; name = "Hege"; Break up a Code Line You can break up a code line within a text string with a backslash. The example below will be displayed properly: document.write("Hello \ World!"); However, you cannot break up a code line like this: document.write \ ("Hello World!");

Page 68: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

68

JavaScript Objects Earlier in this tutorial we have seen that JavaScript has several built-in objects, like String, Date, Array, and more. In addition to these built-in objects, you can also create your own. JavaScript is an object oriented programming language. An OOP language allows you to define your own objects and make your own variable types. An object is just a special kind of data, with a collection of properties and methods. Properties are the values associated with an object. And Methods are actions that can be performed on object. Javascript supports two kinds of Objects: Inbuilt Objects user defined objects or custom object User Defined Objects: The following illustration gives the detail of how to create user defined object in javascript? Let's illustrate with an example: A person is an object. Properties are the values associated with the object. The persons' properties include name, height, weight, age, skin tone, eye color, etc. All persons have these properties, but the values of those properties will differ from person to person. Objects also have methods. Methods are the actions that can be performed on objects. The persons' methods could be eat(), sleep(), work(), play(), etc. Properties The syntax for accessing a property of an object is: objName.propName You can add properties to an object by simply giving it a value. Assume that the personObj already exists - you can give it properties named firstname, lastname, age, and eyecolor as follows: personObj.firstname="John"; personObj.lastname="Doe"; personObj.age=30; personObj.eyecolor="blue"; document.write(personObj.firstname); The code above will generate the following output: John

Page 69: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

69

Methods An object can also contain methods. You can call a method with the following syntax: objName.methodName() Note: Parameters required for the method can be passed between the parentheses. To call a method called sleep() for the personObj: personObj.sleep(); Creating Your Own Objects There are different ways to create a new object: Create a direct instance of an object The following code creates an new instance of an object, and adds four properties to it: personObj=new Object(); personObj.firstname="John"; personObj.lastname="Doe"; personObj.age=50; personObj.eyecolor="blue"; alternative syntax (using object literals): personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}; Adding a method to the personObj is also simple. The following code adds a method called eat() to the personObj: personObj.eat=eat; Create an object constructor Create a function that construct objects: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; }

Page 70: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

70

Inside the function you need to assign things to this.propertyName. The reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're dealing with must be clear). That's what "this" is: the instance of the object at hand. Once you have the object constructor, you can create new instances of the object, like this: var myFather=new person("John","Doe",50,"blue"); var myMother=new person("Sally","Rally",48,"green"); You can also add some methods to the person object. This is also done inside the function: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.newlastname=newlastname; } Note that methods are just functions attached to objects. Then we will have to write the newlastname() function: function newlastname(new_lastname) { this.lastname=new_lastname; } The newlastname() function defines the person's new last name and assigns that to the person. JavaScript knows which person you're talking about by using "this.". So, now you can write: myMother.newlastname("Doe").

Page 71: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

71

Inbuilt Objects : JavaScript Object Hierarchy Many JavaScript objects are contained within each other. JavaScript objects have a container to contained object relationship rather than a class and subclass relationship. Properties are not inherited from one type of object to another. There are two main types of JavaScript objects. Language Objects - Objects provided by the language and are not dependent on other objects. Navigator - Objects provided by the client browser. These objects are all sub objects to the navigator object. Beyond that, objects are those created by the programmer.

Page 72: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

72

JavaScript Objects Introduction JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. Object Oriented Programming JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. JavaScript String Object Describes the javascript string object including its properties and methods while providing code examples. Properties length - The number of characters in the string. prototype - For creating more properties Methods anchor(anchorName) - A string is displayed as an anchor with the name specified. big() - String is displayed in large format. (big tags) document.write("This is BIG text".big()) Is the same as: <BIG>This is BIG text</BIG> Producing: This is BIG text blink() - String is displayed blinking. (blink tags) document.write("This is BLINKING text".blink()) Is the same as: <BLINK>This is BLINKING text</BLINK> Producing: This is BLINKING text bold() - String is displayed in bold characters. (bold tags) document.write("This is BOLD text".bold()) Is the same as: <B>This is BOLD text</B> Producing: This is BOLD text charAt(index) - Returns a string containing the character at the specified location. The example returns the character "r". myname = "George" myname.charAt(3)

Page 73: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

73

fixed() - A string is displayed in Teletype format (teletype tags). document.write("This is TT text".fixed()) Is the same as: <TT>This is TT text</TT> Producing: This is TT text fontcolor(color) - String is displayed in the specified color. document.write("This is RED text".fontcolor("red")) Is the same as: <FONT color="red">This is RED text</FONT> Producing: This is RED text fontsize(size) - String is displayed in the specified font from a value of 1 to 7. document.write("This is SIZE 5 text".fontsize(5)) Is the same as: <FONT size="5">This is SIZE 5 text</FONT> Producing: This is SIZE 5 text indexOf(pattern) - Returns -1 if the value is not found and returns the index of the first character of the first string matching the pattern in the string. The example will return a value of 3. myname = "George" myname.indexOf("r") indexOf(pattern, index) - Returns -1 if the value is not found and returns the index of the first character of the first string matching the pattern in the string. Searching begins at the index value in the string. italics() - String is displayed using the italics tags. document.write("This is ITALICS text".italics()) Is the same as: <I>This is ITALICS text</I> Producing: This is ITALICS text lastIndexOf(pattern) - Returns -1 if the value is not found and returns the index of the first character of the last string matching the pattern in the string. lastIndexOf(pattern, index) - Returns -1 if the value is not found and returns the index of the first character of the last string matching the pattern in the string. Searching begins at the index value in the string. The example will return a value of 5. myname = "George" myname.lastIndexOf("e") link(href) - A string is displayed as a hypertext link. document.write("Computer Technology Documentation Project".link("http://ctdp.tripod.com/")) Is the same as: <A HREF="http://ctdp.tripod.com/">Computer Technology Documentation Project</A> Producing: Computer Technology Documentation Project small() - String is displayed using the small tags.

Page 74: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

74

document.write("This is SMALL text".small()) Is the same as: <SMALL>This is SMALL text</SMALL> Producing: This is SMALL text split(separator) - Splits a string into substrings based on the separator character. In the below example an array called splitValues is created. The splitValues[0] string will be "Day" and the splitValues[0] string will be "Monday". nvpair = new String("Day=Monday") splitValues=nvpair.split("=") strike() - String is displayed using the strikeout tags. document.write("This is STRIKEOUT text".strike()) Is the same as: <STRIKE>This is STRIKEOUT text</STRIKE> Producing: This is STRIKEOUT text sub() - String is displayed using the subscript tags. document.write("This is SUBSCRIPT text".sub()) Is the same as: <SUB>This is SUBSCRIPT text</SUB> Producing: This is SUBSCRIPT text substr(start, length) - Returns the string starting at the "start" index of the string Continuing for the specified length of characters unless the end of the string is found first. The example will return "org". mysite = "Comptechdoc.org" myname.substring(12, 3) substring(start, end) - Returns the string starting at the "start" index of the string and ending at "end" index location, less one. The example will return "org". mysite = "Comptechdoc.org" myname.substring(12,15) sup() - String is displayed using the superscript tags. document.write("This is SUPERSCRIPT text".sup()) Is the same as: <SUP>This is SUPERSCRIPT text</SUP> Producing: This is SUPERSCRIPT text toLowerCase() - Returns a copy of the string with all characters in lower case. toUpperCase() - Returns a copy of the string with all characters in upper case. JavaScript Date Object Describes the JavaScript Date Object including properties, constructors, and methods. Properties

Page 75: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

75

prototype - For creating more properties. Constructors Date() - Use the current date and time to create an instance of the object date. Date(dateString) - Use the date specified by the string to create the instance of the date object. String format is "month day, year hours:minutes:seconds". Date(year, month, day) - Create an instance of date with the specified values. Year is 0 to 99. Date(year, month, day, hours, minutes, seconds) - Create an instance of date with the specified values. Methods getDate() - Get the day of the month. It is returned as a value between 1 and 31. var curdate = new Date() var mday = curdate.getDate() document.write(mday + "<BR>") The above code prints the day of the month. getDay() - Get the day of the week as a value from 0 to 6 var curdate = new Date() var wday = curdate.getDate() document.write(wday + "<BR>") The above code prints the day of the week. getHours() - The value returned is 0 through 23. var curdate = new Date() var hours = curdate.getHours() document.write(hours + "<BR>") The above code prints the hours since midnight. getMinutes() - The value returned is 0 through 59. var curdate = new Date() var minutes = curdate.getMinutes() document.write(minutes + "<BR>") The above code prints the minutes past the hour. getMonth() - Returns the month from the date object as a value from 0 through 11. var curdate = new Date() var month = curdate.getMonth() document.write(month + "<BR>") The above code prints the numeric value of the month. getSeconds() - The value returned is 0 through 59. var curdate = new Date() var seconds = curdate.getSeconds() document.write(seconds + "<BR>") The above code prints the seconds since the last minute. getTime() - The number of milliseconds since January 1, 1970. this function allows you to manipulate the date object based on a millisecond value then convert it back to the

Page 76: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

76

form you want. In the example below, it is used to set a future expiration time of a cookie. var futdate = new Date() var expdate = futdate.getTime() expdate += 3600*1000 //expires in 1 hour(milliseconds) futdate.setTime(expdate) getTimeZoneOffset() - Time zone offset in hours which is the difference between GMT and local time. var curdate = new Date() var offset = curdate.getTimeZoneOffset() document.write(offset + "<BR>") The above code prints the number of hours different between your timezone and GMT. This value may change with daylight savings time.. getYear() - Returns the numeric four digit value of the year. var curdate = new Date() var year = curdate.getYear() document.write(year + "<BR>") The above code prints the numeric value of the year which is currently 2000. parse() - The number of milliseconds after midnight January 1, 1970 till the given date espressed as a string in the example which is IETF format. var curdate = "Wed, 18 Oct 2000 13:00:00 EST" var dt = Date.parse(curdate) document.write(dt + "<BR>") setDate(value) - Set the day of the month in the date object as a value from 1 to 31. setHours(value) - Set the hours in the date object with a value of 0 through 59. setMinutes(value) - Set the minutes in the date object with a value of 0 through 59. setMonth(value) - Set the month in the date object as a value of 0 through 11. setSeconds(value) - Set the seconds in the date object with a value of 0 through 59. setTime(value) - Sets time on the basis of number of milliseconds since January 1, 1970. The below example sets the date object to one hour in the future. var futdate = new Date() var expdate = futdate.getTime() expdate += 3600*1000 //expires in 1 hour(milliseconds) futdate.setTime(expdate) setYear(value) - Set the year in the date instance as a 4 digit numeric value. toGMTString() - Convert date to GMT format in a form similar to "Fri, 29 Sep 2000 06:23:54 GMT". var curdate = new Date() dstring = curdate.toGMTString() document.write(dstring + "<BR>" + curdate.toLocaleString() + "<BR>") The above example produces: Wed, 18 Oct 2000 18:08:11 UTC 10/18/2000 14:08:11 toLocaleString() - Convert date to local time zone format. See the example, above. UTC() - Based on a comma delimited string, the number of milliseconds after midnight January 1, 1970 GMT is returned. The syntax of the string is "year, month, day [, hrs] [,

Page 77: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

77

min] [, sec]". An example is "2000, 9, 29, 5, 43, 0" for Sept 29, 2000 at 5:43:0. The string is considered to be GMT. The hours, minutes, and seconds are optional. document.write(Date.UTC(2000, 9, 29, 5, 43, 0) + " ") The above example produces: 972798180000 JavaScript Array Object Describes the JavaScript aray object including parameters, properties, and methods. Parameters arrayLength elementN - Array element list of values Properties index input length - The quantity of elements in the object. prototype - For creating more properties. Methods chop() - Used to truncate the last character of a all strings that are part of an array. This method is not defined so it must be written and included in your code. var exclamations = new Array("Look out!", "Duck!" ) exclamations.chop() Causes the values of exclamations to become: Look out Duck concat() grep(searchstring) - Takes an array and returns those array element strings that contain matching strings. This method is not defined so it must be written and included in your code. words = new Array("limit","lines","finish","complete","In","Out") inwords = words.grep("in") The array, inwords, will be: lines, finish join(delimiter) - Puts all elements in the array into a string, separating each element with the specified delimiter. words = new Array("limit","lines","finish","complete","In","Out") var jwords = words.join(";") The value of the string jwords is:

Page 78: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

78

limit;lines;finish;complete;In;Out pop() - Pops the last string off the array and returns it. This method is not defined so it must be written and included in your code. words = new Array("limit","lines","finish","complete","In","Out") var lastword = words.pop() The value of the string lastword is: Out push(strings) - Strings are placed at the end of the array. This method is not defined so it must be written and included in your code. words = new Array("limit","lines","finish") words.push("complete","In","Out") The array, words, will be: limit, lines, finish, complete, In, Out reverse() - Puts array elements in reverse order. words = new Array("limit","lines","finish","complete","In","Out") words.reverse() The array, words, will be: Out, In, complete, finish, lines, limit shift() - Decreases array element size by one by shifting the first element off the array and returning it. This method is not defined so it must be written and included in your code. words = new Array("limit","lines","finish","complete","In","Out") word = words.shift() The array, words, will be: In, complete, finish, lines, limit The string word will be: Out sort() - Sorts the array elements in dictionary order or using a compare function passed to the method. words = new Array("limit","lines","finish","complete","In","Out") word = words.sort() The value of words becomes: In,Out,complete,finish,limit,lines splice() - It is used to take elements out of an array and replace them with those specified. In the below example the element starting at element 3 is removed, two of them are removed and replaced with the specified strings. The value returned are those values that are replaced. This method is not defined so it must be written and included in your code. words = new Array("limit","lines","finish","complete","In","Out") words1 = words.splice(3, 2, "done", "On") The value of words becomes: limit, lines, finish, done, On, Out The value of words1 is set to: complete, In split(deliimiter) - Splits a string using the delimiter and returns an array. words = new String("limit;lines;finish;complete;In;Out") var swords = words.split(";") The values in the array swords is:

Page 79: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

79

limit, lines, finish, complete, In, Out unshift() - Places elementa at the start of an array words = new Array("finish","complete","In","Out") word = words.shift("limit","lines") The array, words, will be: limit, lines,finish, complete, In, Out JavaScript Number Object The Number object is an object wrapper for primitive numeric values. Number objects are created with new Number(). Syntax var num = new Number(value); Note: If the value parameter cannot be converted into a number, it returns NaN (Not-a-Number).

Number Object Properties Property Description constructor Returns the function that created the Number object's prototype MAX_VALUE Returns the largest number possible in JavaScript MIN_VALUE Returns the smallest number possible in JavaScript NEGATIVE_INFINITY Represents negative infinity (returned on overflow) POSITIVE_INFINITY Represents infinity (returned on overflow) prototype Allows you to add properties and methods to an object Number Object Methods Method Description toExponential(x) Converts a number into an exponential notation toFixed(x) Formats a number with x numbers of digits after the decimal point toPrecision(x) Formats a number to x length toString() Converts a Number object to a string valueOf() Returns the primitive value of a Number object Constructer: Property Definition and Usage The constructor property returns the function that created the Number object's prototype. Syntax number.constructor Return the function that created the Number object's prototype:

Page 80: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

80

<script type="text/javascript"> var num=new Number(134.5); document.write(num.constructor); </script> The output of the code above will be: function Number() { [native code MAX_VALUE Property Definition and Usage The MAX_VALUE property returns the largest number possible in JavaScript. This static property has a value of 1.7976931348623157e+308. Note: Numbers larger than this are represented as infinity. Syntax Number.MAX_VALUE Example Return the largest number possible in JavaScript. <script type="text/javascript"> document.write(Number.MAX_VALUE); </script> The output of the code above will be: 1.7976931348623157e+308 JavaScript MIN_VALUE Property Definition and Usage The MIN_VALUE property returns the smallest number possible in JavaScript. This static property has a value of 5e-324. Note: Numbers smaller than this are converted to 0. Syntax

Number.MIN_VALUE

The MIN_VALUE property is supported in all major browsers.

Example

Example

Page 81: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

81

Return the smallest number possible in JavaScript: <script type="text/javascript"> document.write(Number.MIN_VALUE); </script>

The output of the code above will be: 5e-324

NEGATIVE_INFINITY Property Definition and Usage The NEGATIVE_INFINITY property represents negative infinity, returned on overflow. Syntax Number.NEGATIVE_INFINITY; Example Create overflow: <script type="text/javascript"> var x=(-Number.MAX_VALUE)*2; if (x==Number.NEGATIVE_INFINITY) { document.write(x); } </script> The output of the code above will be: -Infinity POSITIVE_INFINITY Property Definition and Usage The POSITIVE_INFINITY property represents infinity, returned on overflow. Syntax Number.POSITIVE_INFINITY; Create overflow: <script type="text/javascript"> var x=(Number.MAX_VALUE)*2; if (x==Number.POSITIVE_INFINITY)

Page 82: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

82

{ document.write(x); } </script> The output of the code above will be: Infinity prototype Property Definition and Usage The prototype property allows you to add properties and methods to an object. Note: Prototype is a global property which is available with almost all JavaScript objects. Syntax object.prototype.name=value Example Use the prototype property to add a property to an object: <script type="text/javascript"> function employee(name,jobtitle,born) { this.name=name; this.jobtitle=jobtitle; this.born=born; } var fred=new employee("Fred Flintstone","Caveman",1970); employee.prototype.salary=null; fred.salary=20000; document.write(fred.salary); </script> The output of the code above will be: 20000 toExponential() Method Definition and Usage The toExponential() method converts a number into an exponential notation. Syntax number.toExponential(x) The toExponential() method is supported in all major browsers.

Page 83: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

83

Example

Example Convert a number into an exponential notation: <script type="text/javascript"> var num = new Number(13.3714); document.write(num.toExponential()+"<br />"); document.write(num.toExponential(2)+"<br />"); document.write(num.toExponential(3)+"<br />"); document.write(num.toExponential(10)); </script> The output of the code above will be: 1.33714e+1 1.34e+1 1.337e+1 1.3371400000e+1

toFixed() Method Definition and Usage The toFixed() method formats a number to use a specified number of trailing decimals. The number is rounded up, and nulls are added after the decimal point (if needed), to create the desired decimal length. Syntax number.toFixed(x) Example Format a number: <script type="text/javascript"> var num = new Number(13.3714); document.write(num.toFixed()+"<br />"); document.write(num.toFixed(1)+"<br />"); document.write(num.toFixed(3)+"<br />"); document.write(num.toFixed(10)); </script> The output of the code above will be: 13 13.4 13.371 13.3714000000

Page 84: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

84

toPrecision() Method Definition and Usage The toPrecision() method formats a number to a specified length. A decimal point and nulls are added (if needed), to create the specified length. Syntax number.toPrecision(x) Example Format a number to a specified length: <script type="text/javascript"> var num = new Number(13.3714); document.write(num.toPrecision()+"<br />"); document.write(num.toPrecision(2)+"<br />"); document.write(num.toPrecision(3)+"<br />"); document.write(num.toPrecision(10)); </script> The output of the code above will be: 13.3714 13 13.4 13.37140000 toString() Method Definition and Usage The toString() method converts a Number object to a string. Note: This method is automatically called by JavaScript whenever a Number object needs to be displayed as a string. Syntax number.toString(radix) Example Convert a number to a string, with different bases: <script type="text/javascript"> var num=new Number(15); document.write(num.toString()+"<br />"); document.write(num.toString(2)+"<br />"); document.write(num.toString(8)+"<br />"); document.write(num.toString(16)+"<br />"); </script> The output of the code above will be:

Page 85: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

85

15 1111 17 f valueOf() Method Definition and Usage The valueOf() method returns the primitive value of a Number object. Note: This method is usually called automatically by JavaScript behind the scenes, and not explicitly in code. Syntax number.valueOf() Example Return the primitive value of a Number object: <script type="text/javascript"> var num=new Number(15); document.write(num.valueOf()); </script> The output of the code above will be: 15 JavaScript RegExp Object A regular expression is an object that describes a pattern of characters. Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text. Syntax var txt=new RegExp(pattern,modifiers); or more simply: var txt=/pattern/modifiers; pattern specifies the pattern of an expression modifiers specify if a search should be global, case-sensitive, etc. Modifiers Modifiers are used to perform case-insensitive and global searches: Modifier Description

Page 86: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

86

i Perform case-insensitive matching g Perform a global match (find all matches rather than stopping after

the first match) m Perform multiline matching Brackets Brackets are used to find a range of characters: Expression Description [abc] Find any character between the brackets [^abc] Find any character not between the brackets [0-9] Find any digit from 0 to 9 [A-Z] Find any character from uppercase A to uppercase Z [a-z] Find any character from lowercase a to lowercase z [A-z] Find any character from uppercase A to lowercase z [adgk] Find any character in the given set [^adgk] Find any character outside the given set (red|blue|green) Find any of the alternatives specified Metacharacters Metacharacters are characters with a special meaning: Metacharacter Description . Find a single character, except newline or line terminator \w Find a word character \W Find a non-word character \d Find a digit \D Find a non-digit character \s Find a whitespace character \S Find a non-whitespace character \b Find a match at the beginning/end of a word \B Find a match not at the beginning/end of a word \0 Find a NUL character \n Find a new line character \f Find a form feed character \r Find a carriage return character \t Find a tab character

Page 87: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

87

\v Find a vertical tab character \xxx Find the character specified by an octal number xxx \xdd Find the character specified by a hexadecimal number dd \uxxxx Find the Unicode character specified by a hexadecimal number xxxx Quantifiers Quantifier Description n+ Matches any string that contains at least one n n* Matches any string that contains zero or more occurrences of n n? Matches any string that contains zero or one occurrences of n n{X} Matches any string that contains a sequence of X n's n{X,Y} Matches any string that contains a sequence of X or Y n's n{X,} Matches any string that contains a sequence of at least X n's n$ Matches any string with n at the end of it ^n Matches any string with n at the beginning of it ?=n Matches any string that is followed by a specific string n ?!n Matches any string that is not followed by a specific string n RegExp Object Properties Property Description global Specifies if the "g" modifier is set ignoreCase Specifies if the "i" modifier is set lastIndex The index at which to start the next match multiline Specifies if the "m" modifier is set source The text of the RegExp pattern RegExp Object Methods Method Description compile() Compiles a regular expression exec() Tests for a match in a string. Returns the first match test() Tests for a match in a string. Returns true or false JavaScript global Property

Page 88: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

88

Definition and Usage The global property specifies whether or not the "g" modifier is set. This property returns true if the "g" modifier is set, otherwise it returns false. Syntax RegExpObject.global Example Check whether or not the "g" modifier is set: <script type="text/javascript"> var str="Visit W3Schools!"; var patt1=/W3S/g; if(patt1.global) { document.write("g modifier is set!"); } else { document.write("g modifier is not set!"); } </script> The output of the code above will be: g modifier is set! JavaScript ignoreCase Property Definition and Usage The ignoreCase property specifies whether or not the "i" modifier is set. This property returns true if the "i" modifier is set, otherwise it returns false. Syntax RegExpObject.ignoreCase Example Check whether or not the "i" modifier is set: <script type="text/javascript"> var str="Visit W3Schools!"; var patt1=/W3S/i; if(patt1.ignoreCase) { document.write("i modifier is set!"); } else

Page 89: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

89

{ document.write("i modifier is not set!"); } </script> The output of the code above will be: i modifier is set! lastIndex Property Definition and Usage The lastIndex property specifies the index at which to start the next match. Note: This property only works if the "g" modifier is set. This property returns an integer that specifies the character position immediately after the last match found by exec( ) or test( ) methods. Note: exec( ) and test( ) reset lastIndex to 0 if they do not get a match. Syntax RegExpObject.lastIndex Example Do a global search for "ain" in a string, and output the index after a match is found: <script type="text/javascript"> var str="The rain in Spain stays mainly in the plain"; var patt1=/ain/g; while (patt1.test(str)==true) { document.write("'ain' found. Index now at: "+patt1.lastIndex); document.write("<br />"); } </script> multiline Property Definition and Usage The multiline property specifies whether or not the m modifier is set. This property returns true if the "m" modifier is set, otherwise it returns false. Syntax RegExpObject.multiline Example Check whether or not the "m" modifier is set: <script type="text/javascript"> var str="Visit W3Schools!"; var patt1=/W3S/gi;

Page 90: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

90

if(patt1.multiline) { document.write("m modifier is set!"); } else { document.write("m modifier is not set!"); } </script> The output of the code above will be: m modifier is not set! source Property

Definition and Usage The source property returns the text of the RegExp pattern. Syntax RegExpObject.source Example Return the text of the RegExp pattern: <script type="text/javascript"> var str="Visit W3Schools"; var patt1=/W3S/g; document.write("The text of the RegExp is: " + patt1.source); </script> compile() Method Definition and Usage The compile() method is used to compile a regular expression during execution of a script. The compile() method can also be used to change and recompile a regular expression. Syntax RegExpObject.compile(regexp,modifier)

Parameter Description regexp A regular expression modifier Specifies the type of matching. "g" for a global match, "i" for a case-

insensitive match and "gi" for a global, case-insensitive match

Page 91: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

91

Example Do a global search for "man" in a string, and replace it with "person". Then change the regular expression and replace either "man" or "woman" with "person", with the compile() method: <script type="text/javascript"> var str="Every man in the world! Every woman on earth!"; patt=/man/g; str2=str.replace(patt,"person"); document.write(str2+"<br />"); patt=/(wo)?man/g; patt.compile(patt); str2=str.replace(patt,"person"); document.write(str2); </script> The output of the code above will be: Every person in the world! Every woperson on earth! Every person in the world! Every person on earth! exec() Method Definition and Usage The exec() method tests for a match in a string. This method returns the matched text if it finds a match, otherwise it returns null. Syntax RegExpObject.exec(string)

Parameter Description string Required. The string to be searched Example Do a global search, and test for "Hello" and "W3Schools" in a string: <script type="text/javascript"> var str="Hello world!"; //look for "Hello" var patt=/Hello/g; var result=patt.exec(str); document.write("Returned value: " + result); //look for "W3Schools" patt=/W3Schools/g; result=patt.exec(str); document.write("<br />Returned value: " + result);

Page 92: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

92

</script> The output of the code above will be: Returned value: Hello Returned value: null test() Method Definition and Usage The test() method tests for a match in a string. This method returns true if it finds a match, otherwise it returns false. Syntax RegExpObject.test(string)

Parameter Description string Required. The string to be searched Example Do a global search, and test for "Hello" and "W3Schools" in a string: <script type="text/javascript"> var str="Hello world!"; //look for "Hello" var patt=/Hello/g; var result=patt.test(str); document.write("Returned value: " + result); //look for "W3Schools" patt=/W3Schools/g; result=patt.test(str); document.write("<br />Returned value: " + result); </script> The output of the code above will be: Returned value: true Returned value: false JavaScript Boolean Object Boolean Object The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false). For a tutorial about the Boolean object, read our JavaScript Boolean Object tutorial.

Boolean Object Properties Property Description

Page 93: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

93

constructor Returns the function that created the Boolean object's prototype prototype Allows you to add properties and methods to an object Boolean Object Methods Method Description toString() Converts a Boolean value to a string, and returns the result valueOf() Returns the primitive value of a Boolean object constructor Property Definition and Usage The constructor property returns the function that created the Boolean object's prototype. Syntax boolean.constructor Example Return the function that created the Boolean object's prototype: <script type="text/javascript"> var bool=new Boolean(); document.write(bool.constructor); </script> The output of the code above will be: function Boolean() { [native code] } prototype Property Definition and Usage The prototype property allows you to add properties and methods to any object. Note: Prototype is a global property which is available with almost all JavaScript objects. Syntax object.prototype.name=value Example Use the prototype property to add a property to an object: <script type="text/javascript"> function employee(name,jobtitle,born) { this.name=name; this.jobtitle=jobtitle; this.born=born; }

Page 94: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

94

var fred=new employee("Fred Flintstone","Caveman",1970); employee.prototype.salary=null; fred.salary=20000; document.write(fred.salary); </script> The output of the code above will be: 20000 toString() Method Definition and Usage The toString() method converts a Boolean value to a string, and returns the result. Note: This method is called by JavaScript automatically whenever a Boolean object is used in a situation requiring a string. Syntax boolean.toString() Example Convert a Boolean value to a string: <script type="text/javascript"> var bool = new Boolean(1); document.write(bool.toString()); </script> The output of the code above will be: true valueOf() Method Definition and Usage The valueOf() method returns the primitive value of a Boolean object. Note: This method is usually called automatically by JavaScript behind the scenes, and not explicitly in code. Syntax boolean.valueOf() Example Return the primitive value of a Boolean object: <script type="text/javascript"> var bool = new Boolean(0); document.write(bool.valueOf());

Page 95: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

95

</script> The output of the code above will be: false JavaScript Math Object The JavaScript math object can be invoked without creating an instance of it. Properties Properties are invoked by lines like "Math.PI". E - Euler's constant LN2 - Natural log of the value 2 LN10 - Natural log of the value 10 LOG2E - The base 2 log of euler's constant (e). LOG10E - The base 10 log of euler's constant (e). PI - 3.1428 SQRT1_2 - The square root of one half. SQRT2 - The square root of 2. Methods Methods are invoked by lines like "Math.sin(1)". abs(a) - Returns the absolute value of a. The result value is 23 in the example below. resultval = Math.abs(-23) acos(a) - Returns the angle in radians that has a cosine of the passed value. The value of "resultval" is 90 degrees. resultval = (180/Math.PI) * Math.cos(0) asin(a) - Returns the angle in radians that has a sine of the passed value. The value of "resultval" is 90 degrees. resultval = (180/Math.PI) * Math.sin(1) atan(a) - Returns the angle in radians that has a tangent of the passed value. The "resultval" will be almost 90 degrees. resultval = (180/Math.PI) * Math.atan(100) atan2(x,y) - Returns the polar coordinate angle based on cartesion x and y coordinates. The value is returned in radians. The "resultval" will be 45. resultval = (180/Math.PI) * Math.atan2(1,1) ceil(x) - Rounds up the value of "a" to the next integer. If the value is a already whole number, the return value will be the same as the passed value. The example returns 13. resultval = Math.ceil(12.01) cos(a) - Returns the cosine of "a" specified in radians. To convert radians to degrees, divide by 2*PI and multiply by 360. The example below returns the cosine of 90 degrees which is 0. resultval = Math.cos(90 * Math.PI/180)

Page 96: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

96

exp(a) - Returns Euler's constant to the power of the passed argument. This is the exponential power. The example below will return a number between 9 and 10. resultval = Math.exp(3) floor(a) - Rounds the passed value down to the next lowest integer. If the passed value is already an integer the returned value is the same as the passed value. The value returned in the example is 8. resultval = Math.floor(8.78) log(a) - This function is the opposite of "exp()" returning the natural log of the passed value. In the below example, 3 is the result. resultval = Math.log(Math.exp(3)) max(a,b) - Returns the larger value of a or b. The variable "resultval" below becomes 5. resultval = Math.max(5, 3) min(a,b) - Returns the lower value of a or b. The variable "resultval" below becomes 3. resultval = Math.min(5, 3) pow(a,b) - Takes the value of a to the power b. In the example below the value 5 is multiplied times itself three times for a result of 125 which is placed in the variable "resultval". resultval = Math.pow(5, 3) random() - Returns a random number between 0 and 1. To generate a number from 0 to 9: i1 = Math.round(Math.random() * 3) round(a) - Returns the value of a to the nearest integer. If the values decimal value is .5 or greater the next highest integer value is returned otherwise the next lowest integer is returned. In the example below, 5 is returned. resultval = Math.round(5.3) sin(a) - Returns the sine of "a" specified in radians. To convert radians to degrees, divide by 2*PI and multiply by 360. The example below returns the sine of 90 degrees which is 1. resultval = Math.sin(90 * Math.PI/180) sqrt(a) - Returns the square root of a. the value of "resultval" is 5. resultval = Math.sqrt(25) tan(a) - Returns the tangent of a value in radians which is the value of the sine divided by the cosine. resultval = Math.tan(0)

Page 97: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

97

JavaScript Browser Detection The Navigator object contains information about the visitor's browser. Browser Detection Almost everything in this tutorial works on all JavaScript-enabled browsers. However, there are some things that just don't work on certain browsers - especially on older browsers. Sometimes it can be useful to detect the visitor's browser, and then serve the appropriate information. The Navigator object contains information about the visitor's browser name, version, and more.s The Navigator Object The Navigator object contains all information about the visitor's browser: Example <div id="example"></div> <script type="text/javascript"> txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>"; txt+= "<p>Browser Name: " + navigator.appName + "</p>"; txt+= "<p>Browser Version: " + navigator.appVersion + "</p>"; txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>"; txt+= "<p>Platform: " + navigator.platform + "</p>"; txt+= "<p>User-agent header: " + navigator.userAgent + "</p>"; document.getElementById("example").innerHTML=txt; </script> Navigator Object The Navigator object of JavaScript returns useful information about the visitor's browser and system. Properties

Properties Description appCodeName The code name of the browser. appName The name of the browser (ie: Microsoft Internet Explorer). appVersion Version information for the browser (ie: 4.75 [en] (Win98; U)). cookieEnabled Boolean that indicates whether the browser has cookies enabled.

Page 98: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

98

language Returns the default language of the browser version (ie: en-US). NS and Firefox only.

mimeTypes[] An array of all MIME types supported by the client. NS and Firefox only.

platform[] The platform of the client's computer (ie: Win32). plugins An array of all plug-ins currently installed on the client. NS and

Firefox only. systemLanguage Returns the default language of the operating system (ie: en-us).

IE only. userAgent String passed by browser as user-agent header. (ie: Mozilla/4.0

(compatible; MSIE 6.0; Windows NT 5.1)) userLanguage Returns the preferred language setting of the user (ie: en-ca). IE

only. Methods Note: "[]" surrounding a parameter below means the parameter is optional.

Methods Description javaEnabled() Tests whether Java is enabled. Returns Boolean. plugins.refresh([reload]) Makes newly installed plug-ins available and optionally reloads

open documents that contain plug-ins if "reload" argument is present and set to true.

Example 1- Detecting various versions of IE <script type="text/javascript"> //note: userAgent in IE7 WinXP returns: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727) if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x; var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number if (ieversion>=8) document.write("You're using IE8 or above") else if (ieversion>=7) document.write("You're using IE7.x") else if (ieversion>=6) document.write("You're using IE6.x") else if (ieversion>=5) document.write("You're using IE5.x") } else document.write("n/a") </script>

Page 99: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

99

Window Object

Page 100: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

100

Events Description Onblur Fires when the window loses focus. Onerror Fires when a JavaScript error occurs. By returning true inside this

event, JavaScript errors on the page (if any) are suppressed, with no error messages popping up: window.onerror=function(msg, url, linenumber){ var logerror='Error message: ' + msg + '. Url: ' + url + 'Line Number: ' + linenumber alert(logerror) return true } See "The onerror event of the window object" for full details.

Onfocus Fires when the focus is set on the current window. Onload Fires when the page has finished loading, including images. This is

a popular event to use to run some JavaScript once everything on the page has loaded/ is available: window.onload=function(){ runsomefunction() } The limitation with the above approach is that multiple calls to window.onload on the same page causes all but the last one to be adopted, with each proceeding call overwritten by the one following it. On a page with multiple JavaScripts, this is more likely than not to happen. To overcome this, you can invoke the onload event handler using the DOM methods element.addEventListener() and its counterpart element.attachEvent() in IE. Event handlers defined in this manner will not get overwritten by their counterparts, but instead queued.

Onresize Fires when the window is resized. Onscroll Fires when the window is scrolled. The following shows the

current y coordinate of the upper left corner of the viewable window in the browser's title bar when the page is scrolled: window.onscroll=function(){ var scrollY=window.pageYOffset || document.body.scrollTop document.title=scrollY }

Onbeforeunload Fires when the page is about to be unloaded, prior to window.onunload event firing. Supported in all modern browsers. By setting event.returnValue to a string, the browser will prompt the user whether he/she wants to leave the current page when attempting to: window.onbeforeunload=function(e){ e.returnValue="Any return string here forces a dialog to appear when user leaves this page" } window.location="http://www.google.com" //prompt is invoked

Onunload Fires when the page is unloaded- process cannot be overruled at this point. Often used to run code cleanup routines.

Page 101: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

101

Properties

Properties Description Closed Returns the Boolean variable indicating whether window has been

closed or not. Also see: "Determining whether a browser window is open or not".

defaultStatus Read/write property that reflects the default window status bar message that appears.

document Reference to the current document object. Frames An array referencing all of the frames in the current window,

including IFRAME elements. Use frames.length to probe the number of frames. The following changes the src property of every IFRAME on the page to a blank page: <iframe src="http://google.com"></iframe> <iframe src="http://yahoo.com"></iframe> <script type="text/javascript"> for (var i=0; i<frames.length; i++){ frames[i].location="about:blank" } </script> If the current page is contained in a frame itself and you wish to access another sibling frame, navigate up towards the topmost frameset document first using the parent property of window, for example: parent.frames[0] //access first frame within parent frameset.

History Reference to the History object of JavaScript, which contains information on the URLs the visitor has visited within the window.

innerWidth, innerHeight - Supported in: Firefox/Opera/Safari, but NOT IE.

Returns the width and height, in pixels, of the window's viewable content area, which does not include any toolbar, scrollbars etc. Note: IE equivalents are "document.body.clientWidth" and "document.body.clientHeight"

outerWidth, outerHeight - Supported in: Firefox/Opera/Safari, but NOT IE.

Returns the width and height, in pixels, of the browser window in its entirety, which includes any toolbar, scrollbars etc. No IE equivalents.

Length Returns the number of frames contained in the window, which includes IFRAMEs.

location Returns or sets the location object of JavaScript, which contains

Page 102: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

102

information on the current URL. Name The name of the window as optionally specified when calling

window.open(). Opener Contains a reference to the window that opened the secondary

window via window.open(). This property should be invoked in the secondary window. See "Creating window remotes using the window.opener property".

Parent Reference to the parent frameset window of the current window, assuming current window is a frame. Otherwise, it simply refers to current window.

Self A synonym for the current window. Status A read/write property that allows you to probe and write to the

browser's status bar. Top A synonym for the topmost browser window. Window References the current window. Same as "self." pageXOffset, pageYOffset - Supported in: Firefox/Opera/Safari, but NOT IE.

Returns an integer representing the pixels the current document has been scrolled from the upper left corner of the window, horizontally and vertically, respectively. You can also use window.scrollX and window.scrollY instead for brevity, which are equivalent properties. Note: IE+ equivalents are "document.body.scrollLeft" and "document.body.scrollTop"

screenX, screenY - Supported in: Firefox/Opera/Safari, but NOT IE.

Specifies the x and y coordinates of the window relative to the user's monitor screen. Note: IE+ equivalents are "window.screenLeft" and "window.screenTop"

screenLeft, screenTop - IE only properties

Specifies the x and y coordinates of the window relative to the user's monitor screen.

Methods Note: "[]" surrounding a parameter below means the parameter is optional.

Methods Description alert(msg) Displays an Alert dialog box with the desired message and OK

button. blur() Removes focus from the window in question, sending the window

to the background on the user's desktop. clearInterval(ID) Clears the timer set using var ID=setInterval(). clearTimeout(ID) Clears the timer set using var ID=setTimeout(). close() Closes a window.

Page 103: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

103

confirm(msg) Displays a Confirm dialog box with the specified message and OK and Cancel buttons. Returns either true or false, depending on which button the user has clicked on, for example: var yourstate=window.confirm("Are you sure you are ok?") if (yourstate) //Boolean variable. Sets to true if user pressed "OK" versus "Cancel." window.alert("Good!")

find(string, [casesensitive], [backward]) - Firefox only property

Searches for the "string" within the page, and returns string or false, accordingly. "casesensitive" is a Boolean denoting whether search is case sensitive. "backwards" is a Boolean when set to true, searches the page backwards. Final two optional parameters must be set together or none at all.

focus() Sets focus to the window, bringing it to the forefront on the desktop.

home() - Firefox only property

Navigates the window to the homepage as designated by the user's browser setting.

moveBy(dx, dy) Moves a window by the specified amount in pixels. moveTo(x, y) Moves a window to the specified coordinate values, in pixels. The

following opens a window and centers it on the user's screen: Demo: <script type="text/javascript"> function centeropen(url, winwidth, winheight){ var centerwin=window.open(url, "", "toolbar=1, resize=1, scrollbars=1, status=1") centerwin.resizeTo(winwidth, winheight) centerwin.moveTo(screen.width/2-winwidth/2, screen.height/2-winheight/2) //center window on user's screen } </script> <a href="#" onClick="centeropen('about:blank', 800, 650); return false">Open Window</a>

open(URL, [name], [features], [replace])

Opens a new browser window. "Name" argument specifies a name that you can use in the target attribute of your <a> tag. "Features" allows you to show/hide various aspects of the window interface (more info). "Replace" is a Boolean argument that denotes whether the URL loaded into the new window should add to the window's history list. window.open("http://www.dynamicdrive.com", "", "width=800px, height=600px, resizable")

Page 104: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

104

When defining the features (3rd parameter), separate each feature with a comma (,). Restriction: In IE, an exception is thrown if you try to open a window containing a page from another domain and then try to manipulate that window. For example: var mywin=window.open("http://www.notcurrentdomain.com", "", "width=800px, height=600px, resizable") mywin.moveTo(0, 0) //Not allowed in IE: an exception is thrown. This restriction does not apply in other browsers.

print() Prints the contents of the window or frame. prompt(msg, [input]) Displays a Prompt dialog box with a message. Optional "input"

argument allows you to specify the default input (response) that gets entered into the dialog box. This function returns the string the user has entered: var yourname=window.prompt("please enter your name") alert(yourname)

resizeBy(dx, dy) Resizes a window by the specified amount in pixels. resizeTo(x y) Resizes a window to the specified pixel values. The following will

resize the current window to be maximized on the screen in browsers with no security hang ups over such an operation (IE does and will do nothing): window.resizeTo(screen.availWidth, screen.availHeight) //see also the screen object

scrollBy(dx, dy) Scrolls a window by the specified amount in pixels. scrollTo(x, y) Scrolls a window to the specified pixel values. setInterval(func, interval, [args])

Calls the specified function reference (func) or JavaScript statement(s) repeatedly per the "interval" parameter, in milliseconds (ie: 1000=every 1 second). This method returns a unique ID which can be passed into clearInterval(id) to clear the timer. Use the optional "args" to pass any number of arguments to the function. The following are all valid examples of setInterval(): setInterval(myfunction, 5000) //function reference var timer=setInterval("document.title='Current Second: ' + new Date().getSeconds()", 1000) //statements should be surrounded in quotes) If you need to repeated call a function that accepts parameters, put that function inside an anonymous function: setInterval(function(){myfunction(param)}, 5000)

setTimeout("func", interval, [args])

Calls the specified function reference (func) or JavaScript statement(s) once after the "interval" parameter has expired, in milliseconds (ie: 1000=after 1 second). This method returns a unique ID which can be passed into clearTimeout(id) to clear the timer.

Page 105: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

105

stop() Stops the window from loading. NS4/NS6+ exclusive method. Use the optional "args" to pass any number of arguments to the function.

Window Features in window.open() The below lists the string features you can pass into the "feature" parameter of window.open() to manipulate its interface. Most features support a value of true or false, though in general, simply including the name of the feature implies it should be added to the window (yes), while not including it means it shouldn't (no). Separate each feature with a comma (,).

Feature Description channelmode Specifies if window should be opened in channel mode. IE only. Fullscreen Specifies if window should be opened in full screen mode. IE

only. Height Specifies the height of the window. Left Specifies the x coordinates of the window in pixels. IE only. See

"screenX" as well. location Specifies if the location bar of the window should be included. menubar Specifies if the menu bar of the window should be included. resizable Specifies if window should be resizable. screenX Specifies the x coordinates of the window in pixels. NS only. See

"left" as well. screenY Specifies the x coordinates of the window in pixels. NS only. See

"top" as well. scrollbars Specifies if window should contain scrollbars. status Specifies if the status bar of the window should be included. toolbar Specifies if the toolbar of the window (ie: reload button) should be

included. top Specifies the y coordinates of the window in pixels. IE only. See

"screenY" as well. width Specifies the width of the window.

Page 106: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

106

Window Object properties: closed <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('','','width=200,height=100'); myWindow.document.write("<p>This is 'myWindow'</p>"); } function closeWin() { myWindow.close(); } function checkWin() { if (myWindow.closed) { document.getElementById("msg").innerHTML="'myWindow' has been closed!"; } else { document.getElementById("msg").innerHTML="'myWindow' has not been closed!"; } } </script> </head> <body> <input type="button" value="Open 'myWindow'" onclick="openWin()" /> <input type="button" value="Close 'myWindow'" onclick="closeWin()" /> <br /><br /> <input type="button" value="Has 'myWindow' been closed?" onclick="checkWin()" /> <br /><br /> <div id="msg"></div> </body> </html> defaultststus: <html> <body>

Page 107: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

107

<script type="text/javascript"> window.defaultStatus="This is the default text in the status bar!!" </script> </body> </html> frames: <html> <body> <iframe src="http://microsoft.com"></iframe> <iframe src="http://google.com"></iframe> <iframe src="http://youtube.com"></iframe> <script type="text/javascript"> for (var i=0; i<frames.length; i++) { frames[i].location="http://w3schools.com" } </script> </body> </html> innerheight: <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('',''); myWindow.innerHeight="200"; myWindow.innerWidth="200"; myWindow.document.write("<p>This is 'myWindow'</p>"); myWindow.focus(); } </script> </head> <body> <input type="button" value="Open 'myWindow'" onclick="openWin()" /> </body> </html>

Page 108: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

108

lenght: <html> <body> <iframe src="http://microsoft.com"></iframe> <iframe src="http://google.com"></iframe> <iframe src="http://youtube.com"></iframe> <script type="text/javascript"> for (var i=0; i<frames.length; i++) { frames[i].location="http://w3schools.com" } </script> </body> </html> name: <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('','MsgWindow','width=200,height=100'); myWindow.document.write("<p>This window's name is: " + myWindow.name + "</p>"); } </script> </head> <body> <input type="button" value="Open 'myWindow'" onclick="openWin()" /> </body> </html> opener: <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('','','width=200,height=100'); myWindow.document.write("This is 'myWindow'!"); myWindow.focus(); myWindow.opener.document.write("<p>This is the source window!</p>"); }

Page 109: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

109

</script> </head> <body> <input type="button" value="Open 'myWindow'" onclick="openWin()" /> </body> </html> outheight: <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('',''); myWindow.outerHeight="200"; myWindow.outerWidth="200"; myWindow.document.write("<p>This is 'myWindow'</p>"); myWindow.focus(); } </script> </head> <body> <input type="button" value="Open 'myWindow'" onclick="openWin()" /> </body> </html> pageoffset: <html> <head> <script type="text/javascript"> function scrollWindow() { window.scrollBy(100,100) alert("pageXOffset: " + window.pageXOffset + ", pageYOffset: " + window.pageYOffset) } </script> </head> <body> <input type="button" onclick="scrollWindow()" value="Scroll" /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br />

Page 110: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

110

<br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> </body> </html> PageYOffset: <html> <head> <script type="text/javascript"> function scrollWindow() { window.scrollBy(100,100) alert("pageXOffset: " + window.pageXOffset + ", pageYOffset: " + window.pageYOffset) } </script> </head> <body> <input type="button" onclick="scrollWindow()" value="Scroll" /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br />

Page 111: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

111

<br /> <br /> <br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> </body> </html> Parent <html> <head> <script type="text/javascript"> function openWin() { window.open('','','width=200,height=100'); alert(window.parent.location); } </script> </head> <body> <input type="button" value="Open window" onclick="openWin()" /> </body> </html> screen: Screen Object Properties Property Description availHeight Returns the height of the screen (excluding the Windows Taskbar) availWidth Returns the width of the screen (excluding the Windows Taskbar) colorDepth Returns the bit depth of the color palette for displaying images height Returns the total height of the screen pixelDepth Returns the color resolution (in bits per pixel) of the screen width Returns the total width of the screen <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('',''); myWindow.document.write("<p>This is 'myWindow'");

Page 112: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

112

myWindow.document.write("<br />ScreenLeft: " + myWindow.screenLeft); myWindow.document.write("<br />ScreenTop: " + myWindow.screenTop + "</p>"); } </script> </head> <body> <input type="button" value="Open 'myWindow'" onclick="openWin()" /> </body> </html> screenleft: <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('',''); myWindow.document.write("<p>This is 'myWindow'"); myWindow.document.write("<br />ScreenLeft: " + myWindow.screenLeft); myWindow.document.write("<br />ScreenTop: " + myWindow.screenTop + "</p>"); } </script> </head> <body> <input type="button" value="Open 'myWindow'" onclick="openWin()" /> </body> </html> ScreenX and Screen Y <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('',''); myWindow.document.write("<p>This is 'myWindow'"); myWindow.document.write("<br />ScreenX: " + myWindow.screenX); myWindow.document.write("<br />ScreenY: " + myWindow.screenY + "</p>"); } </script> </head> <body>

Page 113: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

113

<input type="button" value="Open 'myWindow'" onclick="openWin()" /> </body> </html> self: <html> <head> <script type="text/javascript"> function check() { if (window.top!=window.self) { document.write("<p>This window is not the topmost window! Am I in a frame?</p>") } else { document.write("<p>This window is the topmost window!</p>") } } </script> </head> <body> <input type="button" onclick="check()" value="Check window" /> </body> </html> status: <html> <body> <script type="text/javascript"> window.status="Some text in the status bar!!"; </script> </body> </html> top: <html> <head> <script type="text/javascript"> function check() { if (window.top!=window.self) {

Page 114: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

114

document.write("<p>This window is not the topmost window! Am I in a frame?</p>") } else { document.write("<p>This window is the topmost window!</p>") } } </script> </head> <body> <input type="button" onclick="check()" value="Check window" /> </body> </html> METHODS: alert() Method <html> <head> <script type="text/javascript"> function display_alert() { alert("Hello! I am an alert box!!"); } </script> </head> <body> <input type="button" onclick="display_alert()" value="Display alert box" /> </body> </html> BLUR: <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('','','width=200,height=100'); myWindow.document.write("<p>The new window.</p>"); myWindow.blur(); } </script> </head> <body>

Page 115: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

115

<input type="button" value="Open window" onclick="openWin()" /> </body> </html> clearInterval() Method <html> <body> <input type="text" id="clock" /> <script language=javascript> var int=self.setInterval("clock()",1000); function clock() { var d=new Date(); var t=d.toLocaleTimeString(); document.getElementById("clock").value=t; } </script> </form> <button onclick="int=window.clearInterval(int)">Stop</button> </body> </html> clearTimeout() Method <html> <head> <script type="text/javascript"> var c=0; var t; var timer_is_on=0; function timedCount() { document.getElementById('txt').value=c; c=c+1; t=setTimeout("timedCount()",1000); } function doTimer() { if (!timer_is_on) {

Page 116: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

116

timer_is_on=1; timedCount(); } } function stopCount() { clearTimeout(t); timer_is_on=0; } </script> </head> <body> <form> <input type="button" value="Start count!" onclick="doTimer()" /> <input type="text" id="txt" /> <input type="button" value="Stop count!" onclick="stopCount()" /> </form> </body> </html> CLOSE() <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open("","","width=200,height=100"); myWindow.document.write("<p>This is 'myWindow'</p>"); } function closeWin() { myWindow.close(); } </script> </head> <body> <input type="button" value="Open 'myWindow'" onclick="openWin()" /> <input type="button" value="Close 'myWindow'" onclick="closeWin()" /> </body> </html>

Page 117: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

117

CONFIRM() <html> <head> <script type="text/javascript"> function disp_confirm() { var r=confirm("Press a button!") if (r==true) { alert("You pressed OK!") } else { alert("You pressed Cancel!") } } </script> </head> <body> <input type="button" onclick="disp_confirm()" value="Display a confirm box" /> </body> </html> createPopup() Method <html> <head> <script type="text/javascript"> function show_popup() { var p=window.createPopup() var pbody=p.document.body pbody.style.backgroundColor="lime" pbody.style.border="solid black 1px" pbody.innerHTML="This is a pop-up! Click outside to close." p.show(150,150,200,50,document.body) } </script> </head> <body> <button onclick="show_popup()">Create pop-up!</button> </body> </html>

Page 118: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

118

focus() Method <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('','','width=200,height=100'); myWindow.document.write("<p>This is 'myWindow'</p>"); myWindow.focus(); } </script> </head> <body> <input type="button" value="Open window" onclick="openWin()" /> </body> </html> moveBy() Method <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('','','width=200,height=100'); myWindow.document.write("<p>This is 'myWindow'</p>"); } function moveWin() { myWindow.moveBy(250,250); myWindow.focus(); } </script> </head> <body> <input type="button" value="Open 'myWindow'" onclick="openWin()" /> <br /><br /> <input type="button" value="Move 'myWindow'" onclick="moveWin()" /> </body> </html> moveTo() Method

Page 119: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

119

<html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('','','width=200,height=100'); myWindow.document.write("<p>This is 'myWindow'</p>"); } function moveWin() { myWindow.moveTo(0,0); myWindow.focus(); } </script> </head> <body> <input type="button" value="Open 'myWindow'" onclick="openWin()" /> <br /><br /> <input type="button" value="Move 'myWindow'" onclick="moveWin()" /> </body> </html> open() Method Parameter Description

URL Optional. Specifies the URL of the page to open. If no URL is specified, a new window with about:blank is opened

name

Optional. Specifies the target attribute or the name of the window. The following values are supported: _blank - URL is loaded into a new window. This is default _parent - URL is loaded into the parent frame _self - URL replaces the current page _top - URL replaces any framesets that may be loaded name - The name of the window

Specs

Optional. A comma-separated list of items. The following values are supported:

channelmode=yes|no|1|0 Whether or not to display the window in theater mode. Default is no. IE only

directories=yes|no|1|0 Whether or not to add directory buttons. Default is yes. IE only

fullscreen=yes|no|1|0

Whether or not to display the browser in full-screen mode. Default is no. A window in full-screen mode must also be in theater mode. IE only

height=pixels The height of the window. Min. value is 100

Page 120: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

120

left=pixels The left position of the window

location=yes|no|1|0 Whether or not to display the address field. Default is yes

menubar=yes|no|1|0 Whether or not to display the menu bar. Default is yes

resizable=yes|no|1|0 Whether or not the window is resizable. Default is yes

scrollbars=yes|no|1|0 Whether or not to display scroll bars. Default is yes

status=yes|no|1|0 Whether or not to add a status bar. Default is yes

titlebar=yes|no|1|0

Whether or not to display the title bar. Ignored unless the calling application is an HTML Application or a trusted dialog box. Default is yes

toolbar=yes|no|1|0 Whether or not to display the browser toolbar. Default is yes

top=pixels The top position of the window. IE only width=pixels The width of the window. 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: <html> <head> <script type="text/javascript"> function printpage() { window.print() } </script> </head> <body> <input type="button" value="Print this page" onclick="printpage()" /> </body> </html> prompt: Syntax prompt(msg,defaultText)

Page 121: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

121

Parameter Description msg Required. The message to display in the dialog box defaultText Optional. The default input value Example Example Display a prompt box which ask the user for her/his name, and then write a greeting to the page: <html> <head> <script type="text/javascript"> function disp_prompt() { var fname=prompt("Please enter your name:","Your name") document.getElementById("msg").innerHTML="Greetings " + fname } </script> </head> <body> <input type="button" onclick="disp_prompt()" value="Display a prompt box" /> <br /><br /> <div id="msg"></div> </body> </html>

resizeby: resizeBy(width,height) Parameter Description

width Required. A positive or a negative number that specifies how many pixels to resize the width by

height Required. A positive or a negative number that specifies how many pixels to resize the height by

Example Resize the window with 100px each way: <html> <head> <script type="text/javascript"> function resizeWindow() { window.resizeBy(100,100)

Page 122: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

122

} </script> </head> <body> <input type="button" onclick="resizeWindow()" value="Resize window" /> </body> </html>

resizeto: resizeTo(width,height) Parameter Description width Required. Sets the width of the window, in pixels height Required. Sets the height of the window, in pixels Example Example Set the window to a width of 500px, and the height to 300px: <html> <head> <script type="text/javascript"> function resizeWindow() { window.resizeTo(500,300) } </script> </head> <body> <input type="button" onclick="resizeWindow()" value="Resize window" /> </body> </html>

scrollBy(xnum,ynum) Parameter Description xnum Required. How many pixels to scroll by, along the x-axis (horizontal) ynum Required. How many pixels to scroll by, along the y-axis (vertical) Example Scroll the content by 100 pixels: <html> <head>

Page 123: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

123

<script type="text/javascript"> function scrollWindow() { window.scrollBy(100,100) } </script> </head> <body> <input type="button" onclick="scrollWindow()" value="Scroll" /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> </body> </html>

scrollto: scrollTo(xpos,ypos) Parameter Description xpos Required. The coordinate to scroll to, along the x-axis ypos Required. The coordinate to scroll to, along the y-axis Example Scroll the content to position 100,500: <html> <head> <script type="text/javascript">

Page 124: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

124

function scrollWindow() { window.scrollTo(100,500) } </script> </head> <body> <input type="button" onclick="scrollWindow()" value="Scroll" /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <p>SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL SCROLL</p> </body> </html>

setInterval() Method The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds). The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed. The ID value returned by setInterval() is used as the parameter for the clearInterval() method. Tip: 1000 ms = 1 second. Syntax setInterval(code,millisec,lang) Parameter Description code Required. A reference to the function or the code to be executed millisec Required. The intervals (in milliseconds) on how often to execute the

Page 125: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

125

code lang Optional. JScript | VBScript | JavaScript Example Call the clock() function every 1000 millisecond. The clock() function updates the clock. The example also have a button to stop the clock: <html> <body> <input type="text" id="clock" /> <script language=javascript> var int=self.setInterval("clock()",1000); function clock() { var d=new Date(); var t=d.toLocaleTimeString(); document.getElementById("clock").value=t; } </script> </form> <button onclick="int=window.clearInterval(int)">Stop</button> </body> </html>

setTimeout() Method Definition and Usage The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. Tip: 1000 ms = 1 second. Syntax setTimeout(code,millisec,lang) Parameter Description code Required. A reference to the function or the code to be executed

millisec Required. The number of milliseconds to wait before executing the code

lang Optional. The scripting language: JScript | VBScript | JavaScript Example Display an alert box after 3 seconds: <html> <head> <script type="text/javascript"> function timedMsg()

Page 126: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

126

{ var t=setTimeout("alert('I am displayed after 3 seconds!')",3000) } </script> </head> <body> <form> <input type="button" value="Display timed alertbox!" onclick="timedMsg()" /> </form> </body> </html>

Page 127: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

127

JavaScript MimeType Object JavaScript MimeType is a property of the navigator object. Properties description - The description of the MIME type. enabledPlugin - A Plugin object for the MIME type. type - The name describing the MIME type. An example is "text/html". suffixes - File name extensions for specific MIME types, placed in a string. This is a list of file name extensions associated with the mime type. The names are seperated by commas if there are multiple names. JavaScript Plugin Object The JavaScript Plugin object is a property of the navigator object. Properties description - The plug-in description. filename - The plug in file name. length - The quantity of plug in associated MimeType objects. name - The name of the plugin.

Page 128: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

128

Window’s sub Objects: JavaScript Document Object The JavaScript Document object is the container for all HTML HEAD and BODY objects associated within the HTML tags of an HTML document. Document is the parent object of numerous other objects, such as "images", "forms" etc. Properties

Properties Description alinkColor Specifies the color of activated links in the document (Alink

attribute). all[] IE4+ exclusive array that contains all of the elements within

the document. Use document.all["elementID"] or document.all.elementID to access an element.

anchors[] An array containing all of the anchors in the document. applets[] An array containing all of the applets in the document. bgColor Specifies the background color of the document. compatMode Returns the compatibility mode of the current document,

specifically, whether the page is rendered in Quirks or Stricts mode. The two possible values returned are "BackCompat" for Quirks and "CSS1Compat" for Strict. Useful for determining the doctype setting of the page and executing different code accordingly. Example(s): if (document.compatMode=="CSS1Compat") // execute code for page with a valid doctype

cookie A string containing the name/value pair of cookies in the document.

document.documentMode IE8 only property

IE8 property that detects the document mode used by the browser to render the current page. Because IE8 can render a page in various different modes depending on the page's doctype plus the presence of certain HTML elements, documentMode returns a different number depending on the mode the page is being rendered in. They are 5 Page is running in IE5 mode

(aka "quirks mode").

7 Page is running in IE7 standards mode.

Page 129: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

129

8 Page is running in IE8 standards mode.

Microsoft recommends you use documentMode over compatMode to detect a webpage's doctype. See Defining Document Compatibility for more info.

domain Specifies the domain name of the server that served a document. Used for security purposes.

embeds[] An array containing all of the plug-ins in the document, represented using the <embed> tag.

fgColor Specifies the default text color of the document (text attribute).

fileSize Returns the file size of the current document. In IE Windows, a numeric string is returned, while in IE Mac, a number instead. IE only property.

forms[] An array containing all of the forms on the page. images[] An array containing all of the images on the page. lastModified Specifies the last modified date of the document, as reported

by the web server. linkColor Specifies the color of unvisited links in the document (link

attribute). links[] An array containing all of the links on the page. plugins[] Same as embeds[] object. readyState IE property. Supported in Opera 9+, Chrome, and FF 3.6+ as well.

Returns the loading status of the document. It returns one of the below 4 values: uninitialized The document hasn't started

loading yet.

loading The document is loading.

interactive The document has loaded enough whereby user can interact with it.

complete The document has fully loaded.

Use the onreadystatechange event handler to react whenever the readyState of the document changes. For example: document.onreadystatechange=function(){ if (document.readyState=="complete"){ alert("Document loaded fully!") } }

referrer A string that specifies the URL in which the user derived from

Page 130: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

130

to reach the current, usually via a link. title Specifies the title of the document. Read/write in modern

browsers. URL A string that specifies the complete URL of the document. vlinkColor Specifies the color of visited links in the document (vlink

attribute). Methods Note: "[]" surrounding a parameter below means the parameter is optional.

Methods Description close() Closes a document stream opened using document.open(). getElementById("ID") A cross browser (IE5/NS6+) DOM method for accessing any

element on the page via its ID attribute. open([mineType]) Opens a document stream in preparation for document.write() to

write to it. Use the optional "mineType" argument (default is text/html) to specify a specific minetype, such as "image/gif." Example(s).

write("string") Writes to the document (as it's loading) or document stream the "string" entered. Example(s).

writeln("string") Writes to the document (as it's loading) or document stream the "string" entered and inserts a newline character at the end.

Page 131: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

131

Document Object : collecton: anchors[] document.anchors[].property Example 1 Return the number of anchors in the document: <html> <body> <a name="html">HTML Tutorial</a><br /> <a name="css">CSS Tutorial</a><br /> <a name="xml">XML Tutorial</a><br /> <p>Number of anchors: <script type="text/javascript"> document.write(document.anchors.length); </script></p> </body> </html> The output of the code above will be: Number of anchors: 3

forms: document.forms[].property Example 1 Return the number of forms in the document: <html> <body> <form name="Form1"></form> <form name="Form2"></form> <form></form> <p>Number of forms: <script type="text/javascript"> document.write(document.forms.length); </script></p> </body> </html> The output of the code above will be: Number of forms: 3

Page 132: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

132

Example 2 Return the name of the first form in the document: <html> <body> <form name="Form1"></form> <form name="Form2"></form> <form></form> <p>Name of first form: <script type="text/javascript"> document.write(document.forms[0].name); </script></p> </body> </html> The output of the code above will be: Name of first form: Form1

images: document.images[].property Example 1 Return the number of images in the document: <html> <body> <img border="0" src="klematis.jpg" width="150" height="113" /> <img border="0" src="klematis2.jpg" width="152" height="128" /> <p>Number of images: <script type="text/javascript"> document.write(document.images.length); </script></p> </body> </html> The output of the code above will be: Number of images: 2

links Collection Example 1 Return the number of links in the document: <html> <body>

Page 133: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

133

<img src ="planets.gif" width="145" height="126" alt="Planets" usemap ="#planetmap" /> <map name="planetmap"> <area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun" /> <area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury" /> <area shape="circle" coords="124,58,8" href="venus.htm" alt="Venus" /> </map> <p><a href="/js/">JavaScript Tutorial</a></p> <p>Number of areas/links: <script type="text/javascript"> document.write(document.links.length); </script></p> </body> </html> The output of the code above will be: Number of areas/links: 4 Example 2 Return the id of the first link in the document: <html> <body> <img src ="planets.gif" width="145" height="126" alt="Planets" usemap ="#planetmap" /> <map name="planetmap"> <area id="sun" shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun" /> <area id="mercury" shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury" /> <area id="venus" shape="circle" coords="124,58,8" href="venus.htm" alt="Venus" /> </map> <p><a id="javascript" href="/js/">JavaScript Tutorial</a></p> <p>Id of first area/link: <script type="text/javascript"> document.write(document.links[0].id); </script></p> </body> </html>

Page 134: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

134

The output of the code above will be: Id of first area/link: sun Document Object Properties cookie: Example Return the cookies associated with the current document: <html> <body> Cookies associated with this document: <script type="text/javascript"> document.write(document.cookie); </script> </body> </html>

documentMode Property The documentMode property returns the mode used by the browser to render the current document. IE8 can render a page in different modes, depending on the !DOCTYPE or the presence of certain HTML elements. This property returns one of three values: 5 - The page is displayed in IE5 mode 7 - The page is displayed in IE7 mode 8 - The page is displayed in IE8 mode Note: If no !DOCTYPE is specified, IE8 renders the page in IE5 mode! Syntax document.documentMode Example Return the mode used by the browser to render the current document: <html> <body> This document is displayed in: <script type="text/javascript"> document.write(document.documentMode); </script> </body>

Page 135: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

135

</html>

domain Property Example Return the domain name of the server that loaded the document: <html> <body> The domain name for the server that loaded this document: <script type="text/javascript"> document.write(document.domain); </script> </body> </html>

lastModified Property Example Return the date and time the document was last modified: <html> <body> This document was last modified on: <script type="text/javascript"> document.write(document.lastModified); </script> </body> </html>

readyState Property The readyState property returns the (loading) status of the current document. This property returns one of four values: uninitialized - Has not started loading yet loading - Is loading interactive - Has loaded enough and the user can interact with it complete - Fully loaded Syntax document.readyState Example Return the loading status of the current document: <html> <body>

Page 136: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

136

Loading status: <script type="text/javascript"> document.write(document.readyState); </script> </body> </html>

referrer Property Example Return the referrer of the current document: <html> <body> The referrer of this document is: <script type="text/javascript"> document.write(document.referrer); </script> </body> </html>

title Property Example Example Return the title of the current document: <html> <head> <title>My title</title> </head> <body> The title of the document is: <script type="text/javascript"> document.write(document.title); </script> </body> </html>

URL Property Example Return the full URL of the current document:

Page 137: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

137

<html> <body> The full URL of this document is: <script type="text/javascript"> document.write(document.URL); </script> </body> </html>

close() Method Example 1 Open an output stream, add some text, then close the output stream: <html> <head> <script type="text/javascript"> function createDoc() { var doc=document.open("text/html","replace"); var txt="<html><body>Learning about the HTML DOM is fun!</body></html>"; doc.write(txt); doc.close(); } </script> </head> <body> <input type="button" value="New document" onclick="createDoc()" /> </body> </html> Example 2 Open an output stream (in a new window; about:blank), add some text, then close the output stream: <html> <body> <script type="text/javascript"> w=window.open(); w.document.open(); w.document.write("<b>Hello World!</b>"); w.document.close(); </script>

Page 138: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

138

</body> </html>

getElementById() Method document.getElementById("id") Example Alert innerHTML of an element with a specific ID: <html> <head> <script type="text/javascript"> function getValue() { var x=document.getElementById("myHeader"); alert(x.innerHTML); } </script> </head> <body> <h1 id="myHeader" onclick="getValue()">Click me!</h1> </body> </html>

getElementsByName() Method document.getElementsByName(name) Example Alert the number of elements with a specific name: <html> <head> <script type="text/javascript"> function getElements() { var x=document.getElementsByName("x"); alert(x.length); } </script> </head> <body> <input name="x" type="text" size="20" /><br /> <input name="x" type="text" size="20" /><br /> <input name="x" type="text" size="20" /><br /><br /> <input type="button" onclick="getElements()" value="How many elements named 'x'?"

Page 139: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

139

/> </body> </html>

getElementsByTagName() Method document.getElementsByTagName(tagname) Example <html> <head> <script type="text/javascript"> function getElements() { var x=document.getElementsByTagName("input"); alert(x.length); } </script> </head> <body> <input type="text" size="20" /><br /> <input type="text" size="20" /><br /> <input type="text" size="20" /><br /><br /> <input type="button" onclick="getElements()" value="How many input elements?" /> </body> </html>

open() Method document.open(MIMEtype,replace) Parameter Description

MIMEtype Optional. The type of document you are writing to. Default value is "text/html"

replace Optional. If set, the history entry for the new document inherits the history entry from the document which opened this document

Example Open an output stream, add some text, then close the output stream: <html> <head> <script type="text/javascript"> function createDoc() {

Page 140: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

140

var doc=document.open("text/html","replace"); var txt="<html><body>Learning about the HTML DOM is fun!</body></html>"; doc.write(txt); doc.close(); } </script> </head> <body> <input type="button" value="New document" onclick="createDoc()" /> </body> </html> Example 2 Open an output stream (in a new window; about:blank), add some text, then close the output stream: <html> <body> <script type="text/javascript"> w=window.open(); w.document.open(); w.document.write("<h1>Hello World!</h1>"); w.document.close(); </script> </body> </html>

write() Method document.write(exp1,exp2,exp3,...) Parameter Description

exp1,exp2,exp3,... Optional. What to write to the output stream. Multiple arguments can be listed and they will be appended to the document in order of occurrence

Example 1 Write some text to the output stream: <html> <body> <script type="text/javascript"> document.write("Hello World!");

Page 141: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

141

</script> </body> </html>

Example 2 Write some formatted text to the output stream: <html> <body> <script type="text/javascript"> document.write("<h1>Hello World!</h1><p>Have a nice day!</p>"); </script> </body> </html> Example 3 Difference between write() and writeln(): <html> <body> <p>Note that write() does NOT add a new line after each statement:</p> <pre> <script type="text/javascript"> document.write("Hello World!"); document.write("Have a nice day!"); </script> </pre> <p>Note that writeln() add a new line after each statement:</p> <pre> <script type="text/javascript"> document.writeln("Hello World!"); document.writeln("Have a nice day!"); </script> </pre> </body> </html>

writeln() Method

Page 142: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

142

document.writeln(exp1,exp2,exp3,...) Parameter Description

exp1,exp2,exp3,... Optional. What to write to the output stream. Multiple arguments can be listed and they will be appended to the document in order of occurrence

Example Difference between write() and writeln(): <html> <body> <p>Note that write() does NOT add a new line after each statement:</p> <pre> <script type="text/javascript"> document.write("Hello World!"); document.write("Have a nice day!"); </script> </pre> <p>Note that writeln() add a new line after each statement:</p> <pre> <script type="text/javascript"> document.writeln("Hello World!"); document.writeln("Have a nice day!"); </script> </pre> </body> </html>

Page 143: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

143

Location Object: Location contains information about the current URL of the browser. The most common usage of Location is simply to use it to automatically navigate the user to another page: <script type="text/javascript"> window.location="http://www.google.com" </script> Properties

Properties Description We will use the URL

"http://www.mysite.com/good.htm#section2" as basis below to explain the various properties.

hash Specifies the anchor portion of the URL, including the leading hash. (ie: "#section2").

host Specifies the hostname and port (if available) of a URL. (ie: "www.mysite.com" or "www.mysite.com:563").

hostname Specifies the hostname portion of the URL (ie: "www.mysite.com").

href Specifies the entire URL. pathname Specifies the path name of the URL (ie: "/good.htm"). port Specifies the port portion of the URL (ie: "563" within the host

"www.mysite.com:563"). protocol Specifies the protocol portion of the URL, including the trailing

colon (ie: "http:" or "https:"). search Specifies the query portion of the URL, including the question

mark (ie: "?sort=alpha") Methods Note: "[]" surrounding a parameter below means the parameter is optional.

Methods Description reload([forceGet]) Reloads the current document. If "forceGet" set to true, document

is completely reloaded even if server reports it hasn't been modified since last reload. Default is false.

replace(url) Loads the specified URL over the current history entry. Example(s)

Page 144: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

144

Examples replace(url) location.replace("http://www.cnn.com") //Loads CNN.com in browser and overwrites the most recent history entry with it. Location Properties: Hash Example Return the anchor portion of a URL. Assume that the current URL is http://www.example.com/test.htm#part2: <script type="text/javascript"> document.write(location.hash); </script> The output of the code above will be: #part2

host: Example Return the hostname and port of the current URL: <script type="text/javascript"> document.write(location.host); </script> The output of the code above will be: www.w3schools.com

Hostname Property Example Return the hostname of the current URL: <script type="text/javascript"> document.write(location.hostname); </script> The output of the code above will be: www.w3schools.com

href:

Page 145: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

145

Example Return the entire URL (of the current page): <script type="text/javascript"> document.write(location.href); </script> The output of the code above will be: http://www.w3schools.com/jsref/prop_loc_href.asp

pathname: Example Return the path name of the current URL: <script type="text/javascript"> document.write(location.pathname); </script> The output of the code above will be: /jsref/prop_loc_pathname.asp

port Property Example Return the port number of the current URL: <script type="text/javascript"> document.write(location.port); </script> The output of the code above will be: protocol Property Example Return the protocol portion of the current URL: <script type="text/javascript"> document.write(location.protocol); </script> The output of the code above will be: http:

search:

Page 146: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

146

Example Return the query portion of a URL. Assume that the current URL is http://www.example.com/[email protected]: <script type="text/javascript"> document.write(location.search); </script> The output of the code above will be: [email protected]

assign() method Example Load a new document: <html> <head> <script type="text/javascript"> function newDoc() { window.location.assign("http://www.w3schools.com") } </script> </head> <body> <input type="button" value="Load new document" onclick="newDoc()" /> </body> </html>

reload() method Example Reload the current document: <html> <head> <script type="text/javascript"> function reloadPage() { window.location.reload() } </script> </head> <body>

Page 147: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

147

<input type="button" value="Reload page" onclick="reloadPage()" /> </body> </html>

replace() method Example Replace the current document: <html> <head> <script type="text/javascript"> function replaceDoc() { window.location.replace("http://www.w3schools.com") } </script> </head> <body> <input type="button" value="Replace document" onclick="replaceDoc()" /> </body> </html>

Page 148: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

148

History Object: The History object contains an array of previously visited URLs by the visitor. To simulate the browser's back button, for example, you can use the History object: <a href="javascript:history.go(-1)">Go back</a> Properties

Properties Description length Returns the number of URLs in the browser's history list.

Methods

Methods Description back() Loads the previous URL in the history list. forward() Loads the next URL in the history list. go(whereTo) Goes to a specific URL within the history list. "whereTo" can be

an integer to go to a URL within a specific position relative to the current (ie: -1 goes back one page, 1 goes forward one), or a string. For the string, enter a partial or full URL, and the function to match and go to the first URL that matches the string. Example(s).

Properties Of History : length Property Example Return the number of URLs in the history list: <script type="text/javascript"> document.write("Number of URLs in history list: " + history.length); </script> The output of the code above will be: Number of URLs in history list: 6

back() Method Example Create a back button on a page: <html>

Page 149: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

149

<head> <script type="text/javascript"> function goBack() { window.history.back() } </script> </head> <body> <input type="button" value="Back" onclick="goBack()" /> </body> </html> The output of the code above will be: button back

forward () Example Create a forward button on a page: <html> <head> <script type="text/javascript"> function goForward() { window.history.forward() } </script> </head> <body> <input type="button" value="Forward" onclick="goForward()" /> </body> </html> The output of the code above will be: button forward

go() Example Click on the button to go back two pages: <html> <head> <script type="text/javascript">

Page 150: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

150

function goBack() { window.history.go(-2) } </script> </head> <body> <input type="button" value="Go back 2 pages" onclick="goBack()" /> </body> </html> The output of the code above will be: Go back 2 pages

HTML DOM Form Object Form Object: The Form object represents an HTML form.For each <form> tag in an HTML document, a Form object is created.Forms are used to collect user input, and contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain select menus, textarea, fieldset, legend, and label elements.Forms are used to pass data to a server. Form Object Collections Collection Description W3C elements[] Returns an array of all elements in a form Yes Form Object Properties Property Description W3C acceptCharset Sets or returns the value of the accept-charset attribute in a form Yes action Sets or returns the value of the action attribute in a form Yes enctype Sets or returns the value of the enctype attribute in a form Yes length Returns the number of elements in a form Yes method Sets or returns the value of the method attribute in a form Yes name Sets or returns the value of the name attribute in a form Yes target Sets or returns the value of the target attribute in a form Yes Form Object Methods Method Description W3C reset() Resets a form Yes submit() Submits a form Yes

Page 151: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

151

Form Object Events Event The event occurs when... W3C onreset The reset button is clicked Yes onsubmit The submit button is clicked Yes Form elements Collection The elements collection returns an array of all the elements in a form. Syntax formObject.elements[].property Example Return the value of each element in a form: <html> <body> <form id="frm1" action="form_action.asp"> First name: <input type="text" name="fname" value="Donald" /><br /> Last name: <input type="text" name="lname" value="Duck" /><br /> <input type="submit" value="Submit" /> </form> <script type="text/javascript"> var x=document.getElementById("frm1"); for (var i=0;i<x.length;i++) { document.write(x.elements[i].value); document.write("<br />"); } </script> </body> </html> The output of the script above will be: Donald Duck Submit

Form acceptCharset Property The acceptCharset property sets or returns the value of the accept-charset attribute in a form element.The accept-charset attribute specifies the character-sets the server can handle for form-data. Syntax

Page 152: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

152

formObject.acceptCharset=value The acceptCharset property can have the following value: Value Description character-set One or more character-sets that the server can handle. To specify more

than one character set, separate the sets with a comma. Common values: UTF-8 - Character encoding for Unicode ISO-8859-1 - Character encoding for the Latin alphabet In theory, any character encoding can be used, but no browser understands all of them. The more widely a character encoding is used, the better the chance that a browser will understand it. To view all available character encodings, go to our Character sets reference.

The acceptCharset property is supported in all major browsers. Example Return the value of the accept-charset attribute in a form: <html> <body> <form id="frm1" accept-charset="ISO-8859-1"> First name: <input type="text" name="fname" value="Donald" /><br /> Last name: <input type="text" name="lname" value="Duck" /><br /> </form> <script type="text/javascript"> document.write(document.getElementById("frm1").acceptCharset) </script> </body> </html> The output of the script above will be: ISO-8859-1

Form action Property The action property sets or returns the value of the action attribute in a form.The action attribute specifies where to send the form-data when a form is submitted. Syntax formObject.action=URL Example Return the action URL of a form:

Page 153: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

153

<html> <body> <form id="frm1" action="form_action.asp"> First name: <input type="text" name="fname" value="Donald" /><br /> Last name: <input type="text" name="lname" value="Duck" /><br /> <input type="submit" value="Submit" /> </form> <script type="text/javascript"> document.write(document.getElementById("frm1").action); </script> </body> </html> The output of the script above will be: form_action.asp

Form enctype Property The enctype property sets or returns the value of the enctype attribute in a form.The enctype attribute specifies how form-data should be encoded before sending it to the server.The form-data is encoded to "application/x-www-form-urlencoded" by default. This means that all characters are encoded before they are sent to the server (spaces are converted to "+" symbols, and special characters are converted to ASCII HEX values). Syntax formObject.enctype=value The enctype property can have one of the following values: Value Description application/x-www-form-urlencoded

All characters are encoded before sent (this is default)

multipart/form-data No characters are encoded. This value is required when you are using forms that have a file upload control

text/plain Spaces are converted to "+" symbols, but no special characters are encoded

Example Return how form-data should be encoded before sending it to the server: <html> <body> </form> <form id="frm1" enctype="text/plain">

Page 154: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

154

First name: <input type="text" name="fname" value="Donald" /><br /> Last name: <input type="text" name="lname" value="Duck" /><br /> </form> <script type="text/javascript"> document.write(document.getElementById("frm1").enctype); </script> </body> </html> The output of the script above will be: text/plain

Form length Property The length property returns the number of elements in a form. Syntax formObject.length Example Return the number of elements in a form: <html> <body> <form id="frm1" action="form_action.asp"> First name: <input type="text" name="fname" value="Donald" /><br /> Last name: <input type="text" name="lname" value="Duck" /><br /> <input type="submit" value="Submit" /> </form> <script type="text/javascript"> document.write(document.getElementById("frm1").length); </script> </body> </html> The output of the script above will be: 3

Form method Property The method property sets or returns the value of the method attribute in a form.The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute).

Page 155: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

155

Syntax formObject.method=value The method property can have one of the following values: Value Description get Appends the form-data to the URL: URL?name=value&name=value (this is

default) post Sends the form-data as an HTTP post transaction Note: Internet Explorer returns "get" even if no method attribute is defined (this is the default value), while the other browsers return nothing. Example Return the method for sending form data: <html> <body> <form id="frm1" action="form_action.asp" method="get"> First name: <input type="text" name="fname" value="Donald" /><br /> Last name: <input type="text" name="lname" value="Duck" /><br /> <input type="submit" value="Submit" /> </form> <script type="text/javascript"> document.write(document.getElementById("frm1").method); </script> </body> </html> The output of the script above will be: get

Form name Property The name property sets or returns the value of the name attribute in a form.The name attribute specifies the name of a form. Syntax formObject.name=formname Example Return the name of the form: <html> <body>

Page 156: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

156

<form id="frm1" name="form1"> First name: <input type="text" name="fname" value="Donald" /><br /> Last name: <input type="text" name="lname" value="Duck" /><br /> </form> <script type="text/javascript"> document.write(document.getElementById("frm1").name); </script> </body> </html> The output of the script above will be: form1

Form target Property The target property sets or returns the value of the target attribute in a form.The target attribute specifies where to open the action URL. Syntax formObject.target=value The target property can have one of the following values: Value Description _blank Opens in a new window _self Opens in the same frame as it was clicked _parent Opens in the parent frameset _top Opens in the full body of the window framename Opens in a named frame Example Return where to open the action URL: <html> <body> <form id="frm1" action="form_action.asp" target="_blank"> First name: <input type="text" name="fname" value="Donald" /><br /> Last name: <input type="text" name="lname" value="Duck" /><br /> <input type="submit" value="Submit" /> </form> <script type="text/javascript"> document.write(document.getElementById("frm1").target); </script>

Page 157: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

157

</body> </html> The output of the script above will be: _blank

Form reset() Method The reset() method resets the values of all elements in a form (same as clicking the Reset button). Syntax formObject.reset() The reset() method is supported in all major browsers. Example Create a button that resets the form: <html> <head> <script type="text/javascript"> function formReset() { document.getElementById("frm1").reset(); } </script> </head> <body> <form id="frm1"> First name: <input type="text" name="fname" /><br /> Last name: <input type="text" name="lname" /><br /> <input type="button" onclick="formReset()" value="Reset form" /> </form> </body> </html>

Form submit() Method The submit() method submits the form (same as clicking the Submit button). Syntax formObject.submit() Example

Page 158: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

158

Create a button that submits the form: <html> <head> <script type="text/javascript"> function formSubmit() { document.getElementById("frm1").submit(); } </script> </head> <body> <form id="frm1" action="form_action.asp"> First name: <input type="text" name="fname" /><br /> Last name: <input type="text" name="lname" /><br /> <input type="button" onclick="formSubmit()" value="Submit form" /> </form> </body> </html> Form onreset Event The onreset event occurs when the reset button in a form is clicked. Syntax onreset="JavaScriptCode" Parameter Description JavaScriptCode Required. Specifies a JavaScript to be executed when the

event occurs Example Display an alert box when the Reset button is clicked: <form onreset="alert('The form will be reset')"> Firstname: <input type="text" name="fname" value="Donald" /><br /> Lastname: <input type="text" name="lname" value="Duck" /><br /><br /> <input type="reset" value="Reset" /> </form>

Page 159: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

159

Form onsubmit Event The onsubmit event occurs when the submit button in a form is clicked. Syntax onsubmit="JavaScriptCode" Parameter Description JavaScriptCode Required. Specifies a JavaScript to be executed when the

event occurs Example Display an alert box when the Submit button is clicked: <html> <head> <script type="text/javascript"> function greeting() { alert("Welcome " + document.forms["frm1"]["fname"].value + "!") } </script> </head> <body> What is your name?<br /> <form name="frm1" action="submit.htm" onsubmit="greeting()"> <input type="text" name="fname" /> <input type="submit" value="Submit" /> </form> </body> </html>

Sub object’s of FORM object HTML DOM <input type="button"> Object Button Object The <input type="button"> object represents a clickable button in an HTML form.The button type is most often used to activate a JavaScript when a user clicks on the button.For each instance of an <input type="button"> tag in an HTML form, a Button

Page 160: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

160

object is created.You can access a button object by searching through the elements[] array of a form, or by using document.getElementById(). Button Object Properties W3C: W3C Standard. Property Description W3C form Returns a reference to the form that contains the input button Yes name Sets or returns the value of the name attribute of an input button Yes type Returns the type of form element the button is Yes value Sets or returns the value of the value attribute of a button Yes Input Button form Property The form property returns a reference to the form containing the button.This property returns a form object on success. Syntax buttonObject.form Example Return the id of the form containing the button: <html> <body> <form id="form1"> <input type="button" value="Click me!" id="button1" /> </form> <p>The id of the form containing the button is: <script type="text/javascript"> document.write(document.getElementById('button1').form.id); </script></p> </body> </html>

Input Button name Property The name property sets or returns the value of the name attribute of a button.The name attribute specifies the name of a button, and is used to reference form data after it has been submitted, or to reference the element in a JavaScript. Syntax buttonObject.name=name

Page 161: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

161

Example Return the value of the name attribute of a button: <html> <body> <form> <input type="button" id="button1" name="button1" value="Click Me!" /> </form> <p>The name of the button is: <script type="text/javascript"> document.write(document.getElementById('button1').name); </script> </p> </body> </html>

Input Button type Property The type property returns the type of form element the button is.For an input button this property will always return "button". Syntax: buttonObject.type Example Return which type of form element the button is: <html> <body> <form> <input type="button" value="Click me!" id="myButton" /> </form> <p>The input type="button" element is of type: <script type="text/javascript"> document.write(document.getElementById("myButton").type); </script> </p> </body> </html>

Page 162: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

162

Input Button value Property The value property sets or returns the value of the value attribute of a button.The value attribute defines the text that is displayed on the button. Syntax buttonObject.value=value Example Return the text displayed on the button: <html> <body> <form> <input type="button" value="Click me!" id="myButton" /> </form> <p>The text on the button is: <script type="text/javascript"> document.write(document.getElementById("myButton").value); </script> </p> </body> </html>

Methods Of Button Object: blur() Method The blur() method is used to remove focus from an element. HTMLElementObject.blur() The blur() method is supported in all major browsers. Example <html> <head> <style type="text/css"> a:active {color:green} </style> <script type="text/javascript"> function getfocus() { document.getElementById('myAnchor').focus() } function losefocus()

Page 163: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

163

{ document.getElementById('myAnchor').blur() } </script> </head> <body> <a id="myAnchor" href="http://www.w3schools.com">Visit W3Schools.com</a> <br /><br/> <input type="button" onclick="getfocus()" value="Get focus"> <input type="button" onclick="losefocus()" value="Lose focus"> </body> </html> click() Method The click() method simulates a mouse-click on an element. HTMLElementObject.click() Example Simulate a mouse-click on a button on body onload: <html> <head> <script type="text/javascript"> function clickButton() { document.getElementById('button1').click() } function alertMsg() { alert("Button 1 was clicked!") } </script> </head> <body onload="clickButton()"> <form> <input type="button" id="button1" onclick="alertMsg()" value="Button 1" /> </form> </body> </html> focus() Method The focus() method is used to give focus to an element. HTMLElementObject.focus()

Page 164: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

164

The focus() method is supported in all major browsers. Example <html> <head> <style type="text/css"> a:active {color:green} </style> <script type="text/javascript"> function getfocus() { document.getElementById('myAnchor').focus() } function losefocus() { document.getElementById('myAnchor').blur() } </script> </head> <body> <a id="myAnchor" href="http://www.w3schools.com">Visit W3Schools.com</a> <br /><br/> <input type="button" onclick="getfocus()" value="Get focus"> <input type="button" onclick="losefocus()" value="Lose focus"> </body> </html> HTML DOM Reset Object: Reset Object The Reset object represents a reset button in an HTML form.For each <input type="reset"> tag in an HTML form, a Reset object is created.You can access a reset button by searching through the elements[] array of the form, or by using document.getElementById(). Reset Object Properties Property Description W3C alt Sets or returns an alternate text to display if a browser does not

support reset buttons Yes

disabled Sets or returns whether or not a reset button should be disabled Yes form Returns a reference to the form that contains the reset button Yes name Sets or returns the name of a reset button Yes type Returns the type of form element a reset button is Yes

Page 165: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

165

value Sets or returns the text that is displayed on a reset button Yes Reset Object alt Property The alt property sets or returns an alternate text to display if a browser does not support reset buttons. Syntax resetObject.alt=alternate_text Example The following example returns the alt text for a reset button: <html> <body> <form> <input type="reset" alt="Reset button" id="reset1" /> </form> <p>The alt text for the reset button is: <script type="text/javascript"> x=document.getElementById('reset1'); document.write(x.alt); </script></p> </body> </html>

Reset Object disabled Property The disabled property sets or returns whether or not a reset button should be disabled. Syntax resetObject.disabled=true|false Example The following example disables the reset button (try-it example also shows id, value and type): <html> <head> <script type="text/javascript"> function disableButton() { document.getElementById("reset1").disabled=true } </script>

Page 166: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

166

</head> <body> <form> <input type="reset" id="reset1" onclick="disableButton()" /> </form> </body> </html>

Reset Object form Property The form property returns a reference to the form that contains the reset button.This property returns a form object on success. Syntax resetObject.form Example The following example returns the id of the form containing the reset button: <html> <body> <form id="form1"> <input type="reset" id="reset1" /> </form> <p>The id of the form containing the reset button is: <script type="text/javascript"> x=document.getElementById('reset1'); document.write(x.form.id); </script></p> </body> </html>

Reset Object name Property The name property sets or returns the name of a reset button. Syntax resetObject.name=name Example The following example returns the name of a reset button:

Page 167: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

167

<html> <body> <form> <input type="reset" id="reset1" name="reset1" /> </form> <p>The name of the reset button is: <script type="text/javascript"> x=document.getElementById('reset1'); document.write(x.name); </script></p> </body> </html>

Reset Object type Property The type property returns the type of form element. For a reset button object this will always be "reset". Syntax resetObject.type Example Show the form element type of the reset button (try-it example also shows id, value, and disables the reset button): <html> <head> <script type="text/javascript"> function alertType() { alert(document.getElementById("reset1").type) } </script> </head> <body> <form> <input type="reset" id="reset1" onclick="alertType()" /> </form> </body> </html>

Page 168: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

168

Reset Object value Property The value property sets or returns the text that is displayed on the reset button. Syntax resetObject.value=sometext Example Show the value of the reset button (try-it example also shows id, type, and disables the reset button): <html> <head> <script type="text/javascript"> function alertValue() { alert(document.getElementById("reset1").value) } </script> </head> <body> <form> <input type="reset" value="Reset values" id="reset1" onclick="alertValue()" /> </form> </body> </html>

HTML DOM Submit Object Submit Object The Submit object represents a submit button in an HTML form.For each <input type="submit"> tag in an HTML form, a Submit object is created. Example: Form validation You can access a submit button by searching through the elements[] array of the form, or by using document.getElementById(). Submit Object Properties Property Description W3C alt Sets or returns an alternate text to display if a browser does not

support submit buttons Yes

disabled Sets or returns whether or not a submit button should be disabled Yes

Page 169: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

169

form Returns a reference to the form that contains the submit button Yes name Sets or returns the name of a submit button Yes type Returns the type of form element a submit button is Yes value Sets or returns the text that is displayed on a submit button Yes Submit Object alt Property The alt property sets or returns an alternate text to display if a browser does not support submit buttons. Syntax submitObject.alt=alternate_text Example The following example returns the alt text for a submit button: <html> <body> <form> <input type="submit" alt="submit button" id="submit1" /> </form> <p>The alt text for the submit button is: <script type="text/javascript"> x=document.getElementById('submit1'); document.write(x.alt); </script></p> </body> </html>

Submit Object disabled Property The disabled property sets or returns whether or not a submit button should be disabled. Syntax submitObject.disabled=true|false Example Alert id, type, and value of a submit button, and disable button: <html> <head> <script type="text/javascript"> function alertId() {

Page 170: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

170

var txt="Id: " + document.getElementById("submit1").id; txt=txt + ", type: " + document.getElementById("submit1").type; txt=txt + ", value: " + document.getElementById("submit1").value; document.getElementById("submit1").disabled=true; alert(txt); } </script> </head> <body> <form> <input type="submit" id="submit1" value="Show values" onclick="alertId()" /> </form> </body> </html>

Submit Object form Property The form property returns a reference to the form that contains the submit button.This property returns a form object on success. Syntax submitObject.form Example The following example returns the id of the form containing the submit button: <html> <body> <form id="form1"> <input type="submit" id="submit1" /> </form> <p>The id of the form containing the submit button is: <script type="text/javascript"> x=document.getElementById('submit1'); document.write(x.form.id); </script></p> </body> </html>

Submit Object name Property

Page 171: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

171

The name property sets or returns the name of a submit button. Syntax submitObject.name=name Example The following example returns the name of a submit button: <html> <body> <form> <input type="submit" id="submit1" name="submit1" /> </form> <p>The name of the submit button is: <script type="text/javascript"> x=document.getElementById('submit1'); document.write(x.name); </script></p> </body> </html>

Submit Object type Property The type property returns the type of form element. For a submit button object this will always be "submit". Syntax submitObject.type Example Alert id, type, and value of a submit button, and disable button: <html> <head> <script type="text/javascript"> function alertId() { var txt="Id: " + document.getElementById("submit1").id; txt=txt + ", type: " + document.getElementById("submit1").type; txt=txt + ", value: " + document.getElementById("submit1").value; document.getElementById("submit1").disabled=true; alert(txt); } </script> </head>

Page 172: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

172

<body> <form> <input type="submit" id="submit1" value="Show values" onclick="alertId()" /> </form> </body> </html>

Submit Object value Property The value property sets or returns the text that is displayed on the submit button. Syntax submitObject.value=sometext Example Alert id, type, and value of a submit button, and disable button: <html> <head> <script type="text/javascript"> function alertId() { var txt="Id: " + document.getElementById("submit1").id; txt=txt + ", type: " + document.getElementById("submit1").type; txt=txt + ", value: " + document.getElementById("submit1").value; document.getElementById("submit1").disabled=true; alert(txt); } </script> </head> <body> <form> <input type="submit" id="submit1" value="Show values" onclick="alertId()" /> </form> </body> </html>

HTML DOM Text Object Text Object

Page 173: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

173

The Text object represents a text-input field in an HTML form.For each <input type="text"> tag in an HTML form, a Text object is created.You can access a text-input field by searching through the elements[] array of the form, or by using document.getElementById(). Text Object Properties Property Description W3C alt Sets or returns an alternate text to display if a browser does not

support text fields Yes

defaultValue Sets or returns the default value of a text field Yes disabled Sets or returns whether or not a text field should be disabled Yes form Returns a reference to the form that contains the text field Yes maxLength Sets or returns the maximum number of characters in a text field Yes name Sets or returns the name of a text field Yes readOnly Sets or returns whether or not a text field should be read-only Yes size Sets or returns the size of a text field Yes type Returns the type of form element a text field is Yes value Sets or returns the value of the value attribute of a text field Yes Text Object Methods Method Description W3C select() Selects the content of a text field Yes Text Object alt Property The alt property sets or returns an alternate text to display if a browser does not support text fields. Syntax textObject.alt=alternate_text Example The following example returns the alt text for a text field: <html> <body> <form> Email: <input type="text" alt="Email input field" id="email" /> </form> <p>The alt text for the text field is:

Page 174: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

174

<script type="text/javascript"> x=document.getElementById('email'); document.write(x.alt); </script></p> </body> </html>

Text Object defaultValue Property The defaultValue property sets or returns the default value of a text field.Note: The default value is the value specified in the HTML "value" attribute. Syntax textObject.defaultValue=somevalue Example The following example gets the default value of the text field: <html> <head> <script type="text/javascript"> function alertValue() { alert(document.getElementById("text1").defaultValue) } </script> </head> <body> <form> <input type="text" id="text1" value="Hello World!" /> <input type="button" id="button1" onclick="alertValue()" value="Show default value" /> </form> </body> </html> Text Object disabled Property The disabled property sets or returns whether or not a text field should be disabled. Syntax textObject.disabled=true|false

Page 175: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

175

Example The following example disables a text field: <html> <head> <script type="text/javascript"> function disableField() { document.getElementById("text1").disabled=true } </script> </head> <body> <form> <input type="text" id="text1" value="Hello world!" /> <input type="button" id="button1" onclick="disableField()" value="Disable text field" /> </form> </body> </html>

Text Object form Property The form property returns a reference to the form that contains the text field.This property returns a form object on success. Syntax textObject.form Example The following example gets the id of the form the text field belongs to: <html> <body> <form id="form1"> <input type="text" id="text1" /> </form> <p>The id of the form containing the text field is: <script type="text/javascript"> x=document.getElementById('text1'); document.write(x.form.id); </script></p>

Page 176: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

176

</body> </html>

Text Object maxLength Property The maxLength property sets or returns the maximum number of characters in a text field. Syntax textObject.maxLength=number_of_char Example Alert maximum length of a text field: <html> <head> <script type="text/javascript"> function maxLen() { alert(document.getElementById("name").maxLength) } </script> </head> <body> <form> Name: <input type="text" id="name" value="Mickey Mouse" size="20" maxlength="30" /> <br /><br /> <input type="button" onclick="maxLen()" value="Alert maxlength" /> </form> </body> </html>

Text Object name Property The name property sets or returns the name of a text field. Syntax textObject.name=name Example The following example gets the name of the text field:

Page 177: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

177

<html> <body> <form> Email: <input type="text" id="email" name="email" /> </form> <p>The name of the text field is: <script type="text/javascript"> x=document.getElementById('text1'); document.write(x.name); </script></p> </body> </html>

Text Object readOnly Property The readOnly property sets or returns whether or not a text field should be read-only. Syntax textObject.readOnly=true|false Example The following example makes a text field read-only: <html> <head> <script type="text/javascript"> function makeReadOnly() { document.getElementById("text1").readOnly=true } </script> </head> <body> <form> <input type="text" id="text1" value="Hello World!" /> <input type="button" onclick="makeReadOnly()" value="Make read-only" /> </form> </body> </html>

Text Object size Property

Page 178: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

178

The size property sets or returns the size of a text field (in number of characters). Syntax textObject.size=number_of_char Example The following example alerts the size of the text field: <html> <head> <script type="text/javascript"> function fieldSize() { alert(document.getElementById("name").size) } </script> </head> <body> <form> Name: <input type="text" id="name" value="Mickey Mouse" size="20" maxlength="30" /> <br /><br /> <input type="button" onclick="fieldSize()" value="Alert size" /> </form> </body> </html>

Text Object type Property The type property returns the type of form element. For a text field this will always be "text". Syntax textObject.type Example The following example returns which type of form element the text field is: <html> <body> <form> <input type="text" id="text1" /> </form>

Page 179: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

179

<script type="text/javascript"> x=document.getElementById("text1"); document.write("Form element type is: "); document.write(x.type); </script> </body> </html>

Text Object value Property The value property sets or returns the value of a text field. Syntax textObject.value=text Example The following example gets the value of the text field: <html> <head> <script type="text/javascript"> function alertValue() { alert(document.getElementById("text1").value) } </script> </head> <body> <form> <input type="text" id="text1" value="Hello world!" /> <input type="button" id="button1" onclick="alertValue()" value="Show default value" /> </form> </body> </html>

Text Object select() Method The select() method is used to select the content of a text field. Syntax textObject.select()

Page 180: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

180

Example The following example selects the content of a text field: <html> <head> <script type="text/javascript"> function selText() { document.getElementById("myText").select() } </script> </head> <body> <form> <input size="25" type="text" id="myText" value="A cat played with a ball"> <input type="button" value="Select text" onclick="selText()"> </form> </body> </html>

HTML DOM Password Object Password Object The Password object represents a password field in an HTML form.For each <input type="password"> tag in an HTML form, a Password object is created.You can access a password field by searching through the elements[] array of the form, or by using document.getElementById(). Password Object Properties Property

Description W3C

alt Sets or returns an alternate text to display if a browser does not support password fields

Yes

defaultValue Sets or returns the default value of a password field Yes disabled Sets or returns whether or not a password field should be

disabled Yes

form Returns a reference to the form that contains the password field Yes maxLength Sets or returns the maximum number of characters in a password

field Yes

name Sets or returns the name of a password field Yes readOnly Sets or returns whether or not a password field should be read- Yes

Page 181: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

181

only size Sets or returns the size of a password field Yes type Returns the type of form element a password field is Yes value Sets or returns the value of the value attribute of the password

field Yes

Password Object Methods Method Description W3C select() Selects the text in a password field Yes Password alt Property The alt property sets or returns an alternate text to display if a browser does not support password fields. Syntax passwordObject.alt=alternate_text Example The following example returns the alt text for a password field: <html> <body> <form> <input type="password" alt="Password field" id="pwd1" /> </form> <p>The alt text for the password field is: <script type="text/javascript"> x=document.getElementById('pwd1'); document.write(x.alt); </script></p> </body> </html>

Password defaultValue Property The defaultValue property sets or returns the default value of a password field.Note: The default value is the value specified in the HTML "value" attribute. Syntax passwordObject.defaultValue=somevalue

Page 182: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

182

Example The following example gets the default value of the password field: <html> <head> <script type="text/javascript"> function alertValue() { alert(document.getElementById("password1").defaultValue) } </script> </head> <body> <form> <input type="password" id="password1" value="thgrt456" /> <input type="button" id="button1" onclick="alertValue()" value="Show default value" /> </form> </body> </html>

Password disabled Property The disabled property sets or returns whether or not a password field should be disabled. Syntax passwordObject.disabled=true|false Example The following example disables the password field: <html> <head> <script type="text/javascript"> function disablePassword() { document.getElementById("password1").disabled=true } </script> </head>v <body> <form> <input type="password" id="password1" /> <input type="button" id="button1" onClick="disablePassword()" value="Disable password field" /> </form>

Page 183: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

183

</body> </html>

Password form Property The form property returns a reference to the form that contains the password field.This property returns a form object on success. Syntax passwordObject.form Example The following example gets the id of the form the password field belongs to: <html> <body> <form id="form1"> <input type="password" id="password1" /> </form> <p>The id of the form containing the password field is: <script type="text/javascript"> x=document.getElementById('password1'); document.write(x.form.id); </script></p> </body> </html>

Password maxLength Property The maxLength property sets or returns the maximum number of characters allowed in a password field. Syntax passwordObject.maxLength=number_of_chars Example The following example alerts the maximum number of characters allowed in the specified password field: <html> <head> <script type="text/javascript"> function alertLength() {

Page 184: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

184

alert(document.getElementById("password1").maxLength) } </script> </head> <body> <form> <input type="password" id="password1" maxLength="8" /> <input type="button" id="button1" onclick="alertLength()" value="Alert maxLength" /> </form> </body> </html>

Password name Property The name property sets or returns the name of the password field. Syntax passwordObject.name=name Example The following example gets the name of the password field: <html> <body> <form id="form1"> <input type="password" id="password1" name="password1" /> </form> <p>The name of the password field is: <script type="text/javascript"> x=document.getElementById('password1'); document.write(x.name); </script></p> </body> </html>

Password readOnly Property The readOnly property sets or returns whether or not a password field should be read-only. Syntax passwordObject.readOnly=true|false

Page 185: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

185

Example The following example makes a password field read-only: <html> <head> <script type="text/javascript"> function makeReadOnly() { document.getElementById("password1").readOnly=true } </script> </head> <body> <form> <input type="password" id="password1" value="thgrt456" /> <input type="button" onclick="makeReadOnly()" value="Make read-only" /> </form> </body> </html>

Password size Property The size property sets or returns the size of the password field (in number of characters). Syntax passwordObject.size=number_of_chars Example The following example changes the size of the password field: <html> <head> <script type="text/javascript"> function changeSize() { document.getElementById("password1").size=40 } </script> </head> <body> <form> <input type="password" id="password1" /> <input type="button" id="button1" onclick="changeSize()"

Page 186: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

186

value="Change size of the password field" /> </form> </body> </html>

Password type Property The type property returns the type of form element. For a password field this will always be "password". Syntax passwordObject.type Example The following example returns which type of form element the password field is: <html> <body> <form> <input type="password" id="password1" /> </form> <script type="text/javascript"> x=document.getElementById("password1"); document.write("Form element type is: "); document.write(x.type); </script> </body> </html>

Password value Property The value property sets or returns the default value of a password field. Syntax passwordObject.value=text Example The following example gets the default value of the password field: <html> <head> <script type="text/javascript"> function alertValue()

Page 187: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

187

{ alert(document.getElementById("password1").value) } </script> </head> <body> <form> <input type="password" id="password1" value="thgrt456" /> <input type="button" id="button1" onclick="alertValue()" value="Show default value" /> </form> </body> </html> Password select() Method The select() method is used to select the text in a password field. Syntax passwordObject.select() Example The following example selects the text in a password field: <html> <head> <script type="text/javascript"> function selText() { document.getElementById('password1').select() } </script> </head> <body> <form> <input type="password" id="password1" value="thgrt456" /> <input type="button" onclick="selText()" value="Select text" /> </form> </body> </html>

Page 188: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

188

HTML DOM Hidden Object Hidden Object The Hidden object represents a hidden input field in an HTML form.For each <input type="hidden"> tag in an HTML form, a Hidden object is created.You can access a hidden input field by searching through the elements[] array of the form, or by using document.getElementById(). Hidden Object Properties Property Description W3C alt Sets or returns an alternate text to display if a browser does not

support hidden fields Yes

form Returns a reference to the form that contains the hidden field Yes name Sets or returns the name of a hidden field Yes type Returns the type of form element a hidden input field is Yes value Sets or returns the value of the value attribute of the hidden field Yes Hidden alt Property The alt property sets or returns an alternate text to display if a browser does not support hidden input fields. Syntax hiddenObject.alt=alternate_text Example The following example returns the alt text for a hidden input field: <html> <body> <form> <input type="hidden" alt="Hidden field" id="hidden1" /> </form> <p>The alt text for the hidden field is: <script type="text/javascript"> x=document.getElementById('hidden1'); document.write(x.alt); </script></p> </body> </html>

Page 189: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

189

Hidden form Property The form property returns a reference to the form that contains the hidden input field.This property returns a form object on success. Syntax hiddenObject.form Example The following example returns the id of the form the hidden field belongs to: <html> <body> <form id="form1"> <input type="hidden" id="hidden1" /> </form> <p>The id of the form containing the hidden element is: <script type="text/javascript"> x=document.getElementById('hidden1'); document.write(x.form.id); </script></p> </body> </html>

Hidden name Property The name property sets or returns the name of a hidden input field. Syntax hiddenObject.name=name Example The following example returns the name of the hidden field: <html> <body> <form> <input type="hidden" id="hidden1" name="hidden1" /> </form> <p>The name of the hidden field is: <script type="text/javascript"> alert(document.getElementById("hidden1").name) </script></p>

Page 190: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

190

</body> </html>

Hidden type Property The type property returns the type of form element. For a hidden object this will always be "hidden". Syntax hiddenObject.type Example The following example returns which type of form element the hidden field is: <html> <body> <form> <input type="hidden" id="hidden1" /> </form> <script type="text/javascript"> x=document.getElementById("hidden1"); document.write("Form element type is: "); document.write(x.type); </script> </body> </html>

Hidden value Property The value property sets or returns the value of the value attribute of the hidden input field.The value attribute defines the default value of the hidden field. Syntax hiddenObject.value Example The following example gets the value of the hidden field: <html> <head> <script type="text/javascript"> function alertValue() {

Page 191: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

191

alert(document.getElementById("hidden1").value) } </script> </head> <body> <form> <input type="hidden" id="hidden1" value="W3Schools" /> <input type="button" id="button1" onclick="alertValue()" value="Show value of the hidden field" /> </form> </body> </html>

HTML DOM Textarea Object Textarea Object The Textarea object represents a text-area in an HTML form.For each <textarea> tag in an HTML form, a Textarea object is created.You can access a Textarea object by indexing the elements array (by number or name) of the form or by using getElementById(). Textarea Object Properties Property Description W3C cols Sets or returns the width of a textarea Yes defaultValue Sets or returns the default text in a textarea Yes disabled Sets or returns whether or not a textarea should be disabled Yes form Returns a reference to the form that contains the textarea Yes name Sets or returns the name of a textarea Yes readOnly Sets or returns whether or not a textarea should be read-only Yes rows Sets or returns the height of a textarea Yes type Returns the type of the form element Yes value Sets or returns the text in a textarea Yes Textarea Object Methods Method Description W3C select() Selects the text in a textarea Yes

Page 192: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

192

Textarea Object cols Property The cols property sets or returns the width of a text area. Syntax textareaObject.cols=number_of_columns Example The following example changes the width of a text area: <html> <head> <script type="text/javascript"> function changeCols() { document.getElementById('txt1').cols="20"; } </script> </head> <body> <textarea id="txt1"> Hello world....This is a text area </textarea> <br /> <input type="button" onclick="changeCols()" value="Change width" /> </body> </html> Textarea Object defaultValue Property The defaultValue property sets or returns the default value of a text area.Note: The default value of a text area is the text between the <textarea> and </textarea> tags. Syntax textareaObject.defaultValue=text Example The following example alerts the default value of a text area: <html> <head> <script type="text/javascript"> function alertDefaultValue() { alert(document.getElementById('txt1').defaultValue); } </script>

Page 193: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

193

</head> <body> <textarea id="txt1"> Hello world....This is a text area </textarea> <br /> <input type="button" onclick="alertDefaultValue()" value="Alert default value" /> </body> </html> Textarea Object disabled Property The disabled property sets or returns whether or not a text area should be disabled. Syntax textareaObject.disabled=true|false Example The following example disables and enables a text area: <html> <head> <script type="text/javascript"> function disable() { document.getElementById('txt1').disabled=true; } function enable() { document.getElementById('txt1').disabled=false; } </script> </head> <body> <textarea id="txt1"> Hello world....This is a text area </textarea> <br /> <input type="button" onclick="disable()" value="Disable" /> <input type="button" onclick="enable()" value="Enable" /> </body>

Page 194: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

194

Textarea Object form Property The form property returns a reference to the form that contains the text area.This property returns a form object on success. Syntax textareaObject.form Example The following example returns the id of the form the text area belongs to: <html> <body> <form id="form1"> <textarea id="txt1"> Hello world....This is a text area </textarea> </form> <p>The id of the form containing the text area is: <script type="text/javascript"> x=document.getElementById('txt1'); document.write(x.form.id); </script> </p> </body> </html> Textarea Object name Property The name property sets or returns the name of a text area. Syntax textareaObject.name=text Example The following example gets the name of a text area: <html> <head> <script type="text/javascript"> function alertName() { alert(document.getElementById('txt1').name); } </script> </head>

Page 195: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

195

<body> <textarea id="txt1" name="textarea1"> Hello world....This is a text area </textarea> <br /> <input type="button" onclick="alertName()" value="Alert name" /> </body> </html> Textarea Object readOnly Property The readOnly property sets or returns whether or not a text area should be read only. Syntax textareaObject.readOnly=true|false Example The following example sets the text area to be read-only: <html> <head> <script type="text/javascript"> function setReadOnly() { document.getElementById('txt1').readOnly=true; } </script> </head> <body> <textarea id="txt1"> Hello world....This is a text area </textarea> <br /> <input type="button" onclick="setReadOnly()" value="Make read-only" /> </body> </html> Textarea Object rows Property The rows property sets or returns the height of a text area. Syntax

Page 196: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

196

textareaObject.rows=number_of rows Example The following example changes the height of a text area: <html> <head> <script type="text/javascript"> function changeRows() { document.getElementById('txt1').rows="15"; } </script> </head> <body> <textarea id="txt1"> Hello world....This is a text area </textarea> <br /> <input type="button" onclick="changeRows()" value="Change height" /> </body> </html> Textarea Object type Property The type property returns the type of form element. For a text area this will always be "textarea". Syntax textareaObject.type Example The following example returns which type of form element the text area element is: <html> <head> <script type="text/javascript"> function alertType() { alert(document.getElementById('txt1').type); } </script> </head> <body>

Page 197: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

197

<textarea id="txt1"> Hello world....This is a text area </textarea> <br /> <input type="button" onclick="alertType()" value="Alert type" /> </body> </html> Textarea Object value Property The value property sets or returns the text of a text area. Syntax textareaObject.value=text Example The following example returns the text of a text area element: <html> <head> <script type="text/javascript"> function alertValue() { alert(document.getElementById('txt1').value); } </script> </head> <body> <textarea id="txt1"> Hello world....This is a text area </textarea> <br /> <input type="button" onclick="alertValue()" value="Alert value" /> </body> </html> Textarea Object select() Method The select() method is used to select the text in a text area. Syntax textareaObject.select() Example

Page 198: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

198

The following example selects the text in a text area: <html> <head> <script type="text/javascript"> function selText() { document.getElementById("txt1").select() } </script> </head> <body> <textarea id="txt1">Hello world....</textarea> <input type="button" value="Select text" onclick="selText()"> </body> </html> HTML DOM Checkbox Object Checkbox Object The Checkbox object represents a checkbox in an HTML form.Checkboxes let a user select one or more options of a limited number of choices.For each <input type="checkbox"> tag in an HTML form, a Checkbox object is created.You can access a checkbox object by searching through the elements[] array of a form, or by using document.getElementById(). Checkbox Object Properties Property Description W3C checked Sets or returns whether or not a checkbox should be checked Yes defaultChecked Returns the default value of the checked attribute Yes form Returns a reference to the form that contains the checkbox Yes name Sets or returns the value of the name attribute of a checkbox Yes type Returns the type of form element the checkbox is Yes value Sets or returns the value of the value attribute of a checkbox Yes Checkbox checked Property The checked property sets or returns whether or not a checkbox should be checked. Syntax checkboxObject.checked=true|false

Page 199: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

199

Example Check and uncheck a checkbox: <html> <head> <script type="text/javascript"> function check() { document.getElementById("check1").checked=true } function uncheck() { document.getElementById("check1").checked=false } </script> </head> <body> <form> <input type="checkbox" id="check1" /> <input type="button" onclick="check()" value="Check Checkbox" /> <input type="button" onclick="uncheck()" value="Uncheck Checkbox" /> </form> </body> </html>

Checkbox defaultChecked Property The defaultChecked property returns the default value of the checked attribute.This property returns true if the checkbox is checked by default, otherwise it returns false. Syntax checkboxObject.defaultChecked Example The following example returns the default value of the checked attribute: <html> <body> <form> <input type="checkbox" id="myCheck" checked="checked" /> </form>

Page 200: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

200

<script type="text/javascript"> alert(document.getElementById("myCheck").defaultChecked) </script> </body> </html> Checkbox form Property The form property returns a reference to the form containing the checkbox.This property returns a form object on success. Syntax checkboxObject.form Example Return the id of the form containing the checkbox: <html> <body> <form id="form1"> <input type="checkbox" id="check1" /> </form> <p>The id of the form containing the checkbox is: <script type="text/javascript"> document.write(document.getElementById('check1').form.id); </script></p> </body> </html>

Checkbox name Property The name property sets or returns the value of the name attribute of a checkbox.The name attribute specifies the name of a checkbox, and is used to reference form data after it has been submitted, or to reference the element in a JavaScript. Syntax checkboxObject.name=name

Page 201: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

201

Example Return the value of the name attribute of a checkbox: <html> <body> <form> <input type="checkbox" id="check1" name="check1" /> </form> <p>The name of the checkbox is: <script type="text/javascript"> document.write(document.getElementById('check1').name) </script> </p> </body> </html> Checkbox type Property The type property returns the type of form element the checkbox is.For a checkbox object this property will always return "checkbox". Syntax checkboxObject.type Example Return which type of form element the checkbox is: <html> <body> <form> <input type="checkbox" id="check1" /> </form> <p>The checkbox element is of type: <script type="text/javascript"> document.write(document.getElementById("check1").type); </script> </body> </html>

Page 202: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

202

Checkbox value Property The value property sets or returns the value of the value attribute of a checkbox.The value attribute defines the value associated with the input. This is the value sent to the form's action URL. Syntax checkboxObject.value=value Example Return the value associated with a checkbox: <html> <body> <form> <input type="checkbox" id="bike" name="vehicle" value="Bike" /> I have a bike<br /> <input type="checkbox" id="car" name="vehicle" value="Car" /> I have a car </form> <p>The value associated with the first checkbox is: <script type="text/javascript"> document.write(document.getElementById("bike").value) </script> </p> </body> </html>

HTML DOM Radio Object Radio Object The Radio object represents a radio button in an HTML form.For each <input type="radio"> tag in an HTML form, a Radio object is created.You can access a radio object by searching through the elements[] array of the form, or by using document.getElementById(). Radio Object Properties Property Description W3C alt Sets or returns an alternate text to display if a browser does not

support radio buttons Yes

checked Sets or returns the state of a radio button Yes defaultChecked Returns the default state of a radio button Yes disabled Sets or returns whether or not a radio button should be disabled Yes form Returns a reference to the form that contains the radio button Yes

Page 203: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

203

name Sets or returns the name of a radio button Yes type Returns the type of form element a radio button is Yes value Sets or returns the value of the value attribute of the radio button Yes Radio alt Property The alt property sets or returns an alternate text to display if a browser does not support radio buttons. Syntax radioObject.alt=alternate_text Example The following example returns the alt text for the radio buttons: <html> <body> <form> Male: <input id="male" alt="male" type="radio" name="Sex" value="Male" /> <br /> Female: <input id="female" alt="female" type="radio" name="Sex" value="Female" /> </form> <p>The alt text for the radio buttons are: <script type="text/javascript"> document.write(document.getElementById('male').alt); document.write(" and "); document.write(document.getElementById('female').alt); </script></p> </body> </html>

Radio checked Property The checked property sets or returns whether or not a radio button is checked. Syntax radioObject.checked=true|false Example The following example checks and un-checks a radio button: <html> <head>

Page 204: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

204

<script type="text/javascript"> function check() { document.getElementById("radio1").checked=true } function uncheck() { document.getElementById("radio1").checked=false } </script> </head> <body> <form> <input type="radio" id="radio1" /> <input type="button" onclick="check()" value="Check" /> <input type="button" onclick="uncheck()" value="Uncheck" /> </form> </body> </html>

Radio defaultChecked Property The defaultChecked property returns the default value of the checked attribute.This property returns true if the radio button is checked by default, otherwise it returns false. Syntax radioObject.defaultChecked Example The following example returns the default value of the checked attribute: <html> <body> <form> <input type="radio" id="radio1" checked="checked" /> </form> <script type="text/javascript"> alert(document.getElementById("radio1").defaultChecked); </script> </body> </html>

Page 205: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

205

Radio disabled Property The disabled property sets or returns whether or not a radio button should be disabled. Syntax radioObject.disabled=true|false Example The following example disables a radio button: <html> <head> <script type="text/javascript"> function disable() { document.getElementById("gnome").disabled=true } </script> </head> <body> <form> Human: <input id="human" type="radio" name="creature" value="Human" /> <br /> Animal: <input id="animal" type="radio" name="creature" value="Animal" /> <br /> Gnome: <input id="gnome" type="radio" name="creature" value="Gnome" /> <br /><br /> <input type="button" onclick="disable()" value="Disable choice" /> </form> </body> </html>

Radio form Property The form property returns a reference to the form that contains the radio button.This property returns a form object on success. Syntax radioObject.form

Page 206: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

206

Example The following example returns the id of the form the radio button belongs to: <html> <body> <form id="form1"> <input type="radio" id="radio1" /> </form> <p>The id of the form containing the radio button is: <script type="text/javascript"> x=document.getElementById('radio1'); document.write(x.form.id); </script></p> </body> </html>

Radio name Property The name property sets or returns the name of a radio button. Syntax radioObject.name=name Example The following example alerts the name of the radio button: <html> <body> <form> <input type="radio" id="radio1" name="radio1" /> </form> <p>The name of the radio button is: <script type="text/javascript"> x=document.getElementById('radio1'); document.write(x.name); </script></p> </body> </html>

Radio type Property

Page 207: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

207

The type property returns the type of form element. For a radio button object this will always be "radio". Syntax radioObject.type Example The following example returns which type of form element the radio button is: <html> <body> <form> <input type="radio" id="radio1" /> </form> <script type="text/javascript"> x=document.getElementById("radio1"); document.write("Form element type is: "); document.write(x.type); </script> </body> </html>

Radio value Property The value property sets or returns the value of the value attribute of the radio button. Syntax radioObject.value=sometext Example Display the value of a selected radio button: <html> <head> <script type="text/javascript"> function check(browser) { document.getElementById("answer").value=browser } </script> </head> <body> <p>What's your favorite browser:</p> <form>

Page 208: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

208

<input type="radio" name="browser" onclick="check(this.value)" value="Internet Explorer">Internet Explorer<br /> <input type="radio" name="browser" onclick="check(this.value)" value="Firefox">Firefox<br /> <input type="radio" name="browser" onclick="check(this.value)" value="Opera">Opera<br /> <input type="radio" name="browser" onclick="check(this.value)" value="Google Chrome">Google Chrome<br /> <input type="radio" name="browser" onclick="check(this.value)" value="Safari">Safari<br /> <br /> Your favorite browser is: <input type="text" id="answer" size="20"> </form> </body> </html>

HTML DOM Select Object The Select object represents a dropdown list in an HTML form. For each <select> tag in an HTML form, a Select object is created. You can access a Select object by searching through the elements[] array of the form, or by using document.getElementById(). Select Object Collections Collection Description W3C options[] Returns an array of all the options in a dropdown list Yes Select Object Properties Property Description W3C disabled Sets or returns whether or not a dropdown list should be disabled Yes form Returns a reference to the form that contains the dropdown list Yes length Returns the number of options in a dropdown list Yes multiple Sets or returns whether or not multiple items can be selected Yes name Sets or returns the name of a dropdown list Yes selectedIndex Sets or returns the index of the selected option in a dropdown list Yes size Sets or returns the number of visible rows in a dropdown list Yes type Returns the type of form element a dropdown list is Yes Select Object Methods Method Description W3C

Page 209: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

209

add() Adds an option to a dropdown list Yes remove() Removes an option from a dropdown list Yes Select Object options Collection The option collection returns an array of all the options in a dropdown list. Note: There is one element for each <option> tag - starting at 0. Syntax

selectObject.options[]

Example The following example outputs the text of all the options in the dropdown list: <html> <head> <script type="text/javascript"> function getOptions() { var x=document.getElementById("mySelect"); txt="All options: " for (i=0;i<x.length;i++) { txt=txt + "\n" + x.options[i].text; } alert(txt); } </script> </head> <body> <form> Select your favorite fruit: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <br /><br /> <input type="button" onclick="getOptions()" value="Output all options"> </form> </body> </html>

Select Object disabled Property

Page 210: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

210

Definition and Usage The disabled property sets or returns whether or not a dropdown list should be disabled. Syntax selectObject.disabled=true|false Example

Example The following example disables and enables a dropdown list: <html> <head> <script type="text/javascript"> function disable() { document.getElementById("mySelect").disabled=true } function enable() { document.getElementById("mySelect").disabled=false } </script> </head> <body> <form> <select id="mySelect"> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select> <br /><br /> <input type="button" onclick="disable()" value="Disable list"> <input type="button" onclick="enable()" value="Enable list"> </form> </body> </html>

Select Object form Property Definition and Usage The form property returns a reference to the form that contains the dropdown list. Syntax

selectObject.form

Page 211: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

211

Example Get the id of the form that contains the dropdown list: <html> <body> <form id="myForm"> <select id="mySelect"> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select> </form> <p>The id of the form is: <script type="text/javascript"> document.write(document.getElementById("mySelect").form.id) </script> </p> </body> </html>

Select Object length Property The length property returns the number of options in a dropdown list. Syntax selectObject.length=number

Example Get the number of options in the dropdown list: <html> <head> <script type="text/javascript"> function getLength() { alert(document.getElementById("mySelect").length) } </script> </head> <body> <form> <select id="mySelect">

Page 212: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

212

<option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select> <input type="button" onclick="getLength()" value="How many options in the list?"> </form> </body> </html>

Select Object multiple Property The multiple property sets or returns whether or not multiple items can be selected in a dropdown list. Note: Opera 9 cannot set this property in a script (only return it). Syntax selectObject.multiple=true|false

Example Select multiple options in a dropdown list: <html> <head> <script type="text/javascript"> function selectMultiple() { document.getElementById("mySelect").multiple=true } </script> </head> <body> <form> <select id="mySelect" size="4"> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select> <input type="button" onclick="selectMultiple()" value="Select multiple">

Page 213: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

213

</form> </body> </html>

Select Object name Property The name property sets or returns the name of a dropdown list. Syntax selectObject.name=name Example

Example The following example alerts the name of a dropdown list: <html> <head> <script type="text/javascript"> function getName() { alert(document.getElementById("mySelect").name) } </script> </head> <body> <form> <select name="mySelect" id="mySelect"> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select> <input type="button" onclick="getName()" value="Alert name"> </form> </body> </html>

Select Object selectedIndex Property The selectedIndex property sets or returns the index of the selected option in a dropdown list.

Page 214: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

214

Note: If the dropdown list allows multiple selections it will only return the index of the first option selected. Syntax

selectObject.selectedIndex=number

Example The following example alerts the index of the selected option: <html> <head> <script type="text/javascript"> function getIndex() { var x=document.getElementById("mySelect") alert(x.selectedIndex) } </script> </head> <body> <form> Select your favorite fruit: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <br /><br /> <input type="button" onclick="getIndex()" value="Alert index of selected option"> </form> </body> </html>

Select Object size Property The size property sets or returns the number of visible rows in a dropdown list. Note: Opera 9 cannot set this property in a script (only return it). Syntax

selectObject.size=number

Example Change the number of visible rows in a dropdown list: <html> <head> <script type="text/javascript">

Page 215: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

215

function changeSize() { document.getElementById("mySelect").size=4 } </script> </head> <body> <form> <select id="mySelect"> <option>Apple</option> <option>Banana</option> <option>Orange</option> <option>Melon</option> </select> <input type="button" onclick="changeSize()" value="Change size"> </form> </body> </html>

Select Object type Property The type property returns the type of form element a dropdown list is. For a dropdown list it will be "select-one" or "select-multiple". Syntax selectObject.type Example

Example The following example returns the type: <html> <head> <script type="text/javascript"> function getType() { alert(document.getElementById("mySelect").type) } </script> </head> <body> <form> <select id="mySelect">

Page 216: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

216

<option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select> <input type="button" onclick="getType()" value="Alert type of dropdown list"> </form> </body> </html>

Select Object add() Method The add() method is used to add an option to a dropdown list. Syntax selectObject.add(option,before) Parameter Description option Required. Specifies the option to add. Must be an option or optgroup

element before Required. Where to insert the new option (null indicates that the new

option will be inserted at the end of the list)

Example The following example adds a "kiwi" option to the end of the dropdown list: <html> <head> <script type="text/javascript"> function insertOption() { var y=document.createElement('option'); y.text='Kiwi' var x=document.getElementById("mySelect"); try { x.add(y,null); // standards compliant } catch(ex) { x.add(y); // IE only }

Page 217: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

217

} </script> </head> <body> <form> <select id="mySelect"> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select> <input type="button" onclick="insertOption()" value="Insert option" /> </form> </body> </html>

Select Object remove() Method The remove() method is used to remove an option from a dropdown list. selectObject.remove(index) Parameter Description index Required. Specifies the index of the option to remove

Example The following example removes the selected option from the drop down list: <html> <head> <script type="text/javascript"> function removeOption() { var x=document.getElementById("mySelect") x.remove(x.selectedIndex) } </script> </head> <body> <form> <select id="mySelect"> <option>Apple</option>

Page 218: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

218

<option>Pear</option> <option>Banana</option> <option>Orange</option> </select> <input type="button" onclick="removeOption()" value="Remove option"> </form> </body> </html>

JavaScript Button Object: Methods blur() - Takes the focus away from the radio button. click() - This function acts as if the user clicked the button. focus() - Gives the focus to the checkbox. Events onBlur onClick onFocus JavaScript Reset Object Methods blur() - Remove the input focus from the button. click() - Performs the same as though the user clicked the button. focus() - Give the input focus to the button. Events onBlur onClick onFocus JavaScript Submit Object Methods blur() - Removes the input focus from the submit button. click() - Performs the same as though the user clicked the button. focus() - Gives the input focus to the submit button. Events onBlur onClick onFocus JavaScript Checkbox Object Methods blur() - Takes the focus away from the checkbox.

Page 219: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

219

click() - This function acts as if the user clicked the checkbox. This function may be used to undo any user action on a checkbox, such as when a user clicks the box, if this function is called, it will undo the user's action. Also this function may be used to link the clicking of multiple checkboxes together. focus() - Gives the focus to the checkbox. Events onBlur onClick onFocus JavaScript Radio Object Methods blur() - Takes the focus away from the radio button. click() - This function acts as if the user clicked the button. focus() - Gives the focus to the radio button. Events onBlur onClick onFocus JavaScript Text Object Methods blur() - Removes the input focus from the text field. focus() - Give the input focus to the text field. select() - Select the contents of the text field Events onBlur onChange onFocus onSelect JavaScript Password Object Methods blur() - Takes the focus away from the password object. focus() - Gives the focus to the password object. select() - The contents of the password object are selected. Events onBlur onFocus JavaScript TextArea Object Methods blur() - Takes the focus away from the textarea object. focus() - Gives the focus to the textarea object. select() - Selects the contents of the textarea. Events

Page 220: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

220

onBlur onChange onFocus onSelect JavaScript Hidden Object – No Events JavaScript FileUpload Object Methods blur() - Takes the focus away from the form. focus() - Gives the focus to the form. Events onBlur onChange onFocus JavaScript Select Object Methods blur() - Removes the input focus from the selection list. focus() - Gives the input focus to the selection list. Events onBlur onChange onFocus JavaScript Option Object Methods blur()- Remove the focus from the option. focus() - Give the focus to the option. Events onBlur onChange onFocus

Page 221: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

221

JavaScript Cookies A cookie is often used to identify a user. What is a Cookie? A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values. Examples of cookies: Name cookie - The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like "Welcome John Doe!" The name is retrieved from the stored cookie Password cookie - The first time a visitor arrives to your web page, he or she must fill in a password. The password is then stored in a cookie. Next time the visitor arrives at your page, the password is retrieved from the cookie Date cookie - The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday August 11, 2005!" The date is retrieved from the stored cookie Create and Store a Cookie In this example we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web page, he or she will be asked to fill in her/his name. The name is then stored in a cookie. The next time the visitor arrives at the same page, he or she will get welcome message. First, we create a function that stores the name of the visitor in a cookie variable: function setCookie(c_name,value,expiredays) { var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toUTCString()); } The parameters of the function above hold the name of the cookie, the value of the cookie, and the number of days until the cookie expires. In the function above we first convert the number of days to a valid date, then we add the number of days until the cookie should expire. After that we store the cookie name, cookie value and the expiration date in the document.cookie object. Then, we create another function that checks if the cookie has been set: function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1) { c_start=c_start + c_name.length+1;

Page 222: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

222

c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length; return unescape(document.cookie.substring(c_start,c_end)); } } return ""; } The function above first checks if a cookie is stored at all in the document.cookie object. If the document.cookie object holds some cookies, then check to see if our specific cookie is stored. If our cookie is found, then return the value, if not - return an empty string. Last, we create the function that displays a welcome message if the cookie is set, and if the cookie is not set it will display a prompt box, asking for the name of the user: function checkCookie() { username=getCookie('username'); if (username!=null && username!="") { alert('Welcome again '+username+'!'); } else { username=prompt('Please enter your name:',""); if (username!=null && username!="") { setCookie('username',username,365); } } } All together now:

Example <html> <head> <script type="text/javascript"> function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1) { c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length;

Page 223: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

223

return unescape(document.cookie.substring(c_start,c_end)); } } return ""; } function setCookie(c_name,value,expiredays) { var exdate=new Date(); exdate.setDate(exdate.getDate()+expiredays); document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toUTCString()); } function checkCookie() { username=getCookie('username'); if (username!=null && username!="") { alert('Welcome again '+username+'!'); } else { username=prompt('Please enter your name:',""); if (username!=null && username!="") { setCookie('username',username,365); } } } </script> </head> <body onload="checkCookie()"> </body> </html>

The example above runs the checkCookie() function when the page loads.

Page 224: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

224

JavaScript Timing Events JavaScript can be executed in time-intervals. This is called timing events. JavaScript Timing Events With JavaScript, it is possible to execute some code after a specified time-interval. This is called timing events. It's very easy to time events in JavaScript. The two key methods that are used are: setTimeout() - executes a code some time in the future clearTimeout() - cancels the setTimeout() Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window object. The setTimeout() Method Syntax var t=setTimeout("javascript statement",milliseconds); The setTimeout() method returns a value - In the statement above, the value is stored in a variable called t. If you want to cancel this setTimeout(), you can refer to it using the variable name. The first parameter of setTimeout() is a string that contains a JavaScript statement. This statement could be a statement like "alert('5 seconds!')" or a call to a function, like "alertMsg()". The second parameter indicates how many milliseconds from now you want to execute the first parameter. Note: There are 1000 milliseconds in one second. Example When the button is clicked in the example below, an alert box will be displayed after 5 seconds.

Example <html> <head> <script type="text/javascript"> function timedMsg() { var t=setTimeout("alert('5 seconds!')",5000); } </script> </head> <body> <form> <input type="button" value="Display timed alertbox!" onClick="timedMsg()" />

Page 225: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

225

</form> </body> </html>

Example - Infinite Loop To get a timer to work in an infinite loop, we must write a function that calls itself. In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0. Notice that we also have a function that checks if the timer is already running, to avoid creating additional timers, if the button is pressed more than once:

Example <html> <head> <script type="text/javascript"> var c=0; var t; var timer_is_on=0; function timedCount() { document.getElementById('txt').value=c; c=c+1; t=setTimeout("timedCount()",1000); } function doTimer() { if (!timer_is_on) { timer_is_on=1; timedCount(); } } </script> </head> <body> <form> <input type="button" value="Start count!" onClick="doTimer()"> <input type="text" id="txt" /> </form> </body> </html>

Page 226: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

226

The clearTimeout() Method Syntax clearTimeout(setTimeout_variable) Example The example below is the same as the "Infinite Loop" example above. The only difference is that we have now added a "Stop Count!" button that stops the timer:

Example <html> <head> <script type="text/javascript"> var c=0; var t; var timer_is_on=0; function timedCount() { document.getElementById('txt').value=c; c=c+1; t=setTimeout("timedCount()",1000); } function doTimer() { if (!timer_is_on) { timer_is_on=1; timedCount(); } } function stopCount() { clearTimeout(t); timer_is_on=0; } </script> </head> <body> <form> <input type="button" value="Start count!" onClick="doTimer()"> <input type="text" id="txt">

Page 227: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

227

<input type="button" value="Stop count!" onClick="stopCount()"> </form> </body> </html>

A clock created by Timing Events: <html> <script type="text/javascript"> function startTime() { var today=new Date(); var h=today.getHours(); var m=today.getMinutes(); var s=today.getSeconds(); // add a zero in front of numbers<10 m=checkTime(m); s=checkTime(s); document.getElementById('txt').innerHTML=h+":"+m+":"+s; t=setTimeout('startTime()',500); } <head> function checkTime(i) { if (i<10) { i="0" + i; } return i; } </script> </head> <body onload="startTime()"> <div id="txt"></div> </body> </html> JavaScript Form Validation JavaScript Form Validation JavaScript can be used to validate data in HTML forms before sending off the content to a server. Form data that typically are checked by a JavaScript could be: has the user left required fields empty? has the user entered a valid e-mail address? has the user entered a valid date? has the user entered text in a numeric field?

Page 228: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

228

Required Fields The function below checks if a required field has been left empty. If the required field is blank, an alert box alerts a message and the function returns false. If a value is entered, the function returns true (means that data is OK): function validate_required(field,alerttxt) { with (field) { if (value==null||value=="") { alert(alerttxt);return false; } else { return true; } } } The entire script, with the HTML form could look something like this: <html> <head> <script type="text/javascript"> function validate_required(field,alerttxt) { with (field) { if (value==null||value=="") { alert(alerttxt);return false; } else { return true; } } } function validate_form(thisform) { with (thisform) { if (validate_required(email,"Email must be filled out!")==false) {email.focus();return false;} }

Page 229: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

229

} </script> </head> <body> <form action="submit.htm" onsubmit="return validate_form(this)" method="post"> Email: <input type="text" name="email" size="30"> <input type="submit" value="Submit"> </form> </body> </html>

E-mail Validation The function below checks if the content has the general syntax of an email. This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character after the @ sign: function validate_email(field,alerttxt) { with (field) { apos=value.indexOf("@"); dotpos=value.lastIndexOf("."); if (apos<1||dotpos-apos<2) {alert(alerttxt);return false;} else {return true;} } } The entire script, with the HTML form could look something like this: <html> <head> <script type="text/javascript"> function validate_email(field,alerttxt) { with (field) { apos=value.indexOf("@"); dotpos=value.lastIndexOf("."); if (apos<1||dotpos-apos<2) {alert(alerttxt);return false;} else {return true;} } }

Page 230: TYBCA- 302 UNIT – 1 JAVASCRIPTJavaScript Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer,

230

function validate_form(thisform) { with (thisform) { if (validate_email(email,"Not a valid e-mail address!")==false) {email.focus();return false;} } } </script> </head> <body> <form action="submit.htm" onsubmit="return validate_form(this);" method="post"> Email: <input type="text" name="email" size="30"> <input type="submit" value="Submit"> </form> </body> </html>

--------------