Вы находитесь на странице: 1из 110

JavaScript

Atul Kahate

akahate@gmail.com

What is JavaScript?

Designed to add interactivity to HTML pages Scripting language (Lightweight programming language) Embedded directly in HTML pages Interpreted language Open software (Free) Supported by all major browsers, like Netscape and Internet Explorer
JavaScript 2

Java and JavaScript

Are Java and JavaScript the same?

NO!

Java and JavaScript are two completely different languages! Java (developed by Sun Microsystems) is a powerful and very complex programming language - in the same category as C and C++
JavaScript 3

JavaScript Capabilities

Programming tool - Scripting language with a very simple syntax Dynamic text into an HTML page - Example: document.write("<h1>" + name + "</h1>") Reacting to events - Execute when something happens, like when a page has finished loading or when a user clicks on an HTML element Read and write HTML elements - A JavaScript can read and change the content of an HTML element Validate data - A JavaScript can be used to validate form data before it is submitted to a server, this will save the server from extra processing
JavaScript 4

Simple Example
<html> <body> <script type="text/javascript"> document.write("Hello World!") </script> </body> </html>
JavaScript 5

Example with a Header


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

Where to Put JavaScript?

Scripts 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, other times when a user triggers an event
JavaScript 7

Controlling When a JavaScript Should Execute 1

Scripts in the head section

Scripts to be executed when they are called, or when an event is triggered, go in the head section When we place a script in the head section, we will ensure that the script is loaded before anyone uses it

JavaScript

Controlling When a JavaScript Should Execute 2

Scripts in the body section

Scripts to be executed when the page loads go in the body section When we place a script in the body section it generates the content of the page

JavaScript

Controlling When a JavaScript Should Execute 3

Scripts in the head and body sections

We can place an unlimited number of scripts in our document, so we can have scripts in both the body and the head section.

JavaScript

10

External JavaScript
<html> <head> </head> <body> <script src="xxx.js"></script> </body> </html>
JavaScript 11

Script in the head element


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

</body> </html>

JavaScript

12

Script in the Body Element


<html> <head> </head> <body>

<script type="text/javascript"> document.write("This message is written when the page loads") </script>
</body> </html>

JavaScript

13

JavaScript Variables

Rules for Variable names:

Syntaxes

Variable names are case sensitive They must begin with a letter or the underscore character var strname = some value strname = some value
var strname = Ram" strname = Ram"
JavaScript 14

Examples

Variables Scope

Local variables

When 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 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
JavaScript 15

Global variables

JavaScript Operators

Arithmetic

+ - * / % ++ -= += -= *= /= %= == != < > <= >= && || !

Assignment

Comparison

Logical

String joining
JavaScript 16

JavaScript Functions

A function contains some code that will be executed by an event or a call to that function A function is a set of statements You can reuse functions within the same script, or in other documents You define functions at the beginning of a file (in the head section), and call them later in the document Example

alert("This is a message")

JavaScript

17

Function Syntaxes

Function with arguments

Function without arguments


function myfunction() { some statements }

function myfunction(argument1,argument2,etc) { some statements }

A function can return a value by using the return statement


JavaScript 18

Example of a Function Call


function total(a,b) { result=a+b return result }

sum=total(2,3)
JavaScript 19

JavaScript Conditional Statements

if statement - use this statement if you want to execute a set of code when a condition is true if...else statement - use this statement if you want to select one of two sets of lines to execute switch statement - use this statement if you want to select one of many sets of lines to execute
JavaScript 20

if Example
<script type="text/javascript"> //If the time on your browser is less than 10, //you will get a "Good morning" greeting. var d=new Date() var time=d.getHours() if (time<10) { document.write("<b>Good morning</b>") } </script>
JavaScript 21

if-else Example
<script type="text/javascript"> //If the time on your browser 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>

JavaScript

22

Statements, II

The switch statement:

switch (expression) { case label : statement; break; case label : statement; break; ... default : statement; }

Other familiar statements:


break; continue; The empty statement, as in ;; or { }

switch Example
<script type="text/javascript"> //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: Case 0: document.write("Super Weekend") break default: document.write("I'm looking forward to this weekend!") } </script> JavaScript 25

Conditional Operator

Syntax

variablename=(condition)?value1:value2

Example

greeting=(visitor=="PRES")?"Dear President ":"Dear "

JavaScript

26

JavaScript Loops

while - loops through a block of code while a condition is true do...while - loops through a block of code once, and then repeats the loop while a condition is true for - run statements a specified number of times
JavaScript 27

for Example
html> <body> <script type="text/javascript"> for (i = 0; i <= 5; i++) { document.write("The number is " + i) document.write("<br>") } </script> <p>Explanation:</p> <p>The for loop sets <b>i</b> equal to 0.</p> <p>As long as <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p> <p><b>i</b> will increase by 1 each time the loop runs.</p> </body> </html>

JavaScript

28

while Example
<html> <body> <script type="text/javascript"> i=0 while (i <= 5) { document.write("The number is " + i) document.write("<br>") i++ } </script> <p>Explanation:</p> <p><b>i</b> equal to 0.</p> <p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p> <p><b>i</b> will increase by 1 each time the loop runs.</p> </body> </html>

JavaScript

29

do-while Example
<html> <body> <script type="text/javascript"> i=0 do { document.write("The number is " + i) document.write("<br>") i++ } while (i <= 5) </script> <p>Explanation:</p> <p><b>i</b> equal to 0.</p> <p>The loop will run</p> <p><b>i</b> will increase by 1 each time the loop runs.</p> <p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p> </body> </html>

JavaScript

30

JavaScript Objects

Array Boolean Date Math String

JavaScript

31

Arrays

Syntax

var family_names=new Array(3) var family_names=new Array("Tove","Jani","Stale")

OR

Accesing array elements family_names[0]="Tove" family_names[1]="Jani" family_names[2]="Stale"


JavaScript 32

Some of the Array Methods


Method concat() reverse() shift() slice(begin[,end]) sort() Description Joins two or more arrays and returns a new array Reverses the order of the elements in an array Removes and returns the first element of an array Creates a new array from a selected section of an existing array Sorts the elements of an array

JavaScript

33

Boolean Object

The Boolean object is an object wrapper for a Boolean value and it is used to convert a non-Boolean value to a Boolean value Example: Initialize to null

Example: Initialize to a non-null value


var var var var var var var var var

b1=new b2=new b3=new b4=new b5=new b1=new b2=new b3=new b4=new

Boolean() Boolean(0) Boolean(null) Boolean("") Boolean(false)

Boolean(true) Boolean("true") Boolean("false") Boolean("Richard")

JavaScript

34

Date Object 1

Get todays date

<html> <body> <script type="text/javascript"> var d = new Date() document.write(d.getDate()) document.write(".") document.write(d.getMonth() + 1) document.write(".") document.write(d.getFullYear()) </script> </body> </html>
JavaScript 35

Date Object 2

Set year, month, day values

<html> <body> <script type="text/javascript"> var d = new Date() d.setFullYear("1990") document.write(d) </script> </body> </html>
JavaScript 36

Date Object 3

Display the day of the week (Sunday, )

<html> <body> <script type="text/javascript"> var d=new Date() var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday"," Friday","Saturday") document.write("Today is " + weekday[d.getDay()]) </script> </body> </html>
JavaScript 37

Date Object 4

Display date in the format Tuesday 7 Dec 2004

<html> <body> <script type="text/javascript"> var d=new Date() var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturda y") var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec") document.write(weekday[d.getDay()] + " ") document.write(monthname[d.getMonth()] + " ") document.write(d.getFullYear()) </script> </body> </html>
JavaScript 38

Summary of Date Functions


Method Date() getDate() getDay() getMonth() getFullYear() getYear() getHours() getMinutes() getSeconds() Description Returns a Date object Returns the date of a Date object (from 1-31) Returns the day of a Date object (from 0-6. 0=Sunday, 1=Monday, etc.) Returns the month of a Date object (from 0-11. 0=January, 1=February, etc.) Returns the year of a Date object (four digits) Returns the year of a Date object (from 0-99). Use getFullYear instead Returns the hour of a Date object (from 0-23) Returns the minute of a Date object (from 0-59) Returns the second of a Date object (from 0-59) JavaScript 39

JavaScript Math Object

The built-in Math object includes mathematical constants and functions We do not need to create the Math object before using it Example

r_number=Math.round(8.6) r_number=Math.random()
JavaScript 40

Math Example 1
<html> <body> <script type="text/javascript"> document.write(Math.round(7.25)) </script> </body> </html>
JavaScript 41

Math Example 2
<html> <body> <script type="text/javascript"> document.write(Math.max(2,4)) </script> </body> </html>
JavaScript 42

Math Object Methods


Method abs(x) cos(x) exp(x) Description Returns the absolute value of x Returns the cosine of x Returns the value of E raised to the power of x

log(x)
max(x,y) min(x,y) pow(x,y) random()

Returns the natural log of x


Returns the number with the highest value of x and y Returns the number with the lowest value of x and y Returns the value of the number x raised to the power of y Returns a random number between 0 and 1

round(x)
sin(x) sqrt(x) tan(x)

Rounds x to the nearest integer


Returns the sine of x Returns the square root of x Returns the tangent of x
JavaScript 43

JavaScript String Object


Method bold() charAt(index) concat() italics() replace() search() substr() substring() toLowerCase() toUpperCase() Description Returns a string in bold Returns the character at a specified position Returns two concatenated strings Returns a string in italic Replaces some specified characters with some new specified characters Returns an integer if the string contains some specified characters, if not it returns -1 Returns the specified characters. 14,7 returns 7 characters, from the 14th character (starts at 0) Returns the specified characters. 7,14 returns all characters from the 7th up to but not including the 14th (starts at 0) Converts a string to lower case Converts a string to upper case

JavaScript

44

JavaScript Guidelines

Case sensitive Needs matching closing tags Ignores extra spaces Special characters need to be prefixed with a backslash (\)

e.g. document.write ("You \& I sing \"Happy Birthday\".")

Comments: // and /* */
JavaScript 45

HTML DOM

What is HTML DOM?

The HTML DOM is a programming interface for HTML documents The HTML DOM defines how you can access and change the content of HTML documents DOM stands for the Document Object Model The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML objects
JavaScript 47

Why HTML DOM?

Because we need an easy and standard way to access the content of HTML documents, that can be used by all types of browsers, and all types of programming languages

e.g. JavaScript can use DOM APIs to access contents of HTML documents

The HTML DOM defines how to access HTML elements, and how to change, add, or delete their content, attributes and styles
JavaScript 48

DOM Parts

DOM Core
Allows parsing of HTML documents

XML DOM
Allows parsing of XML documents

(X)HTML DOM
Allows parsing of XHTML documents

We shall study HTML DOM


JavaScript 49

DOM Example
<html> <head> <script type="text/javascript"> function ChangeColor() { document.body.bgColor="yellow" } </script> </head> <body onclick="ChangeColor()"> Click on this document! </body> </html> Result: After the document is displayed in the browser window; if the user clicks in the browser, the background color would change to yellow. JavaScript 50

Document Objects

DOM views an HTML document as a collection of objects Sample objects

Document object is the parent of all the other objects in an HTML document Document.body object represents the <body> element of the HTML document Meaning: Document object is the parent of the body object, and the body object is a child of the document object.
JavaScript 51

Object Properties/Attributes

HTML document objects can have properties (also called attributes) e.g. document.body.bgColor property defines the background color of the body object. The statement document.body.bgColor="yellow sets the background color of the HTML document to yellow
JavaScript 52

Object Events

HTML document objects can respond to events The onclick="ChangeColor()" defines an action to take place when the user clicks on the document

JavaScript

53

Important Objects from DOM Set

JavaScript

54

Button Object

The button object represents a push button on an HTML form For each instance of an HTML <input type="button"> tag on an HTML form, a Button object is created The Button objects are stored in the elements array of the corresponding form We can access a Button object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute
JavaScript 55

Button Example
<html> <head> <script type="text/javascript"> function show_alert() { alert("Hello World!") document.all("myButton").focus() } </script> </head> <body> <form> <input type="button" value="Click me!" name="myButton" onClick="show_alert()" /> </form> </body> </html>

JavaScript

56

Checkbox Object

The Checkbox object represents a checkbox on an HTML form For each instance of an HTML <input type="checkbox"> tag on an HTML form, a Checkbox object is created All Checkbox objects are stored in the elements array of the corresponding form We can access a Checkbox object by indexing this array - either by number (0 represents the first element in a form) or by using the value of the name attribute
JavaScript 57

Checkbox Example
<html> <head> <script type="text/javascript"> function check() { coffee=document.forms[0].coffee answer=document.forms[0].answer txt="" for (i=0;i<coffee.length;++ i) { if (coffee[i].checked) txt=txt + coffee[i].value + " " } answer.value="You ordered a coffee with " + txt } </script> </head> <body> <form> How would you like your coffee?<br /><br /> <input type="checkbox" name="coffee" value="cream">With cream<br /> <input type="checkbox" name="coffee" value="sugar">With sugar<br /> <br /> <input type="button" name="test" onclick="check()" value="Send order"> <br /><br /> <input type="text" name="answer" size="50"> </form> </body> </html>

JavaScript

58

Document Object

The Document object is used to access all elements in a page Contains many collections, properties, methods, and events

No example for this

JavaScript

59

Event Object

Represents the state of an event, such as the element in which the event occurred, the state of the keyboard keys, the location of the mouse, and the state of the mouse buttons Is available only during an event - that is, you can use it in event handlers but not in other code In VBScript, you must access the event object through the window object
JavaScript 60

Event Example 1
<html> <head> <script type="text/javascript"> function whichButton() { if (event.button==1) alert("You clicked the left mouse button!") else alert("You clicked the right mouse button!") } </script> </head> <body onmousedown="whichButton()"> <p>Click in the document. An alert box will alert which mouse button you clicked.</p> </body> </html>
JavaScript 61

Event Example 2
<html> <head> <script type="text/javascript"> function isKeyPressed() { if (event.shiftKey==1) alert("The shift key was pressed!") else alert("The shift key was NOT pressed!") } </script> </head> <body onmousedown="isKeyPressed()"> <p>Click somewhere in the document. An alert box will tell you if you pressed the shift key or not.</p> </body> </html> JavaScript 62

Form Object

Forms are used to prompt users for input We may use form elements such as text fields, radio buttons, checkboxes and selection lists The input data is normally posted to a server for processing
JavaScript 63

Form Example
<html> <head> <script type="text/javascript"> function formSubmit() { document.forms.myForm.submit() } </script> </head> <body> <form name="myForm" action="js_form_action.asp" method="get"> Firstname: <input type="text" name="firstname" size="20"><br /> Lastname: <input type="text" name="lastname" size="20"><br /><br /> <input type="button" onclick="formSubmit()" value="Submit"> </form> </body> </html> JavaScript 64

Forms Example with Inputs


<html> <head> </head> <body> <FORM name="fm"> Type your first name: <INPUT type="text" name="first"><br> Type your last name: <INPUT type="text" name="last"> <INPUT type="button" name="dis" value="Display" onClick='alert("You say your name is: "+document.fm.first.value+" "+document.fm.last.value)'> </FORM> </body> </html>
JavaScript 65

Form Example 1 (Page 1 of 3)


<html> <head> <script type="text/javascript"> function validate() { x=document.myForm at=x.email.value.indexOf("@") code=x.code.value firstname=x.fname.value submitOK="True" if (at==-1) { alert("Not a valid e-mail!") submitOK="False" }
JavaScript 66

Form Example 1 (Page 2 of 3)


if (code<1 || code>5) { alert("The value must be between 1 and 5") submitOK="False" } if (firstname.length>10) { alert("Your name must be less than 10 characters") submitOK="False" } if (submitOK=="False") { return false } } </script> </head>
JavaScript 67

Form Example 1 (Page 3 of 3)


<body> <form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()"> Enter your e-mail: <input type="text" name="email" size="20"><br /> Enter a value from 1 to 5: <input type="text" name="code" size="20"><br /> Enter your name, max 10 chararcters: <input type="text" name="fname" size="20"><br /> <input type="submit" value="Submit"> </form> </body> </html>
JavaScript 68

Form Example 2
<html> <head> <script type="text/javascript"> function check(browser) { document.forms[0].answer.value=browser } </script> </head> <body> <form> Select which browser is your favorite:<br /><br /> <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="Netscape">Netscape<br /> <input type="radio" name="browser" onclick="check(this.value)" value="Opera">Opera<br /> <br /> <input type="text" name="answer" size="20"> </form> </body> </html>

JavaScript

69

Option Object 1

For each instance of an HTML <option> tag in a selection list on a form, an Option object is created An option in a selection list can be created either with the HTML <option> tag

<option>Wolksvagen</option>

OR

Using the option constructor and assign it to an index of the relevant Select object

document.myForm.cartypes[3]=new Option("Wolksvagen")
JavaScript 70

Option Object 2

To specify a value to be returned to the server when an option is selected and the form submitted

document.myForm.cartypes[3]=new Option("Wolksvagen")

To make the option selected by default in the selection list

document.myForm.cartypes[3]=new Option("Wolksvagen")
JavaScript 71

Option Example - 1
<html> <head> <script type="text/javascript"> function makeDisable() { var x=document.getElementById("mySelect") x.disabled=true } function makeEnable() { var x=document.getElementById("mySelect") x.disabled=false } </script> </head>

<body> <form> <select id="mySelect"> <option>Apple</option> <option>Grape</option> <option>Orange</option> <script type="text/javascript"> document.forms[0].mySelect[3]=new Option("Mango") </script>

</select> <input type="button" onclick="makeDisable()" value="Disable list"> <input type="button" onclick="makeEnable()" value="Enable list"> </form> </body>
</html>

JavaScript

72

Option Example - 2
<html> <head> <script type="text/javascript"> function getText() { var x=document.getElementById("mySelect") alert(x.options[x.selectedIndex].text) } </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="getText()" value="Show text of selected fruit"> </form> </body> </html> JavaScript 73

Option Example - 3
html> <head> <script type="text/javascript"> function getIndex() { var x=document.getElementById("mySelect") alert(x.options[x.selectedIndex].index) } </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="Show index of selected fruit"> </form> </body> JavaScript 74

Option Example - 4
<html> <head> <script type="text/javascript"> function changeText() { var x=document.getElementById("mySelect") x.options[x.selectedIndex].text="Melon" } </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="changeText()" value="Change text of selected fruit"> </form> </body> </html> JavaScript 75

Option Example - 5
<html> <head> <script type="text/javascript"> function changeText() { var x=document.getElementById("mySelect") x.options[x.selectedIndex].text="Melon" } </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="changeText()" value="Change text of selected fruit"> </form> </body> </html> JavaScript 76

Pop up boxes

Three types

Alert Box

Syntax: alert (Your message) A pop-up screen appears User needs to select OK to proceed Syntax: confirm (Your message) User needs to select OK or Cancel

Confirm Box

Prompt Box

User needs to type something and then select OK or Cancel


JavaScript 77

Alert Box Example


<html> <head> </head> <script type="text/javascript"> alert("Please acknowledge this first!"); </script> <body> <H1> Test page </H1> Hello world! </body> </html>
JavaScript 78

Confirm Box Example


<html> <head> </head> <script type="text/javascript"> if (confirm("Do you agree")) {alert("You agree")} else {alert ("You do not agree")}; </script> <body> <H1> My shop </H1> Good bye! </body> </html>

JavaScript

79

Exercises

JavaScript

80

Problem 1

Requirement: Allow the user to enter some text in a textbox and validate to ensure that it is not empty.

JavaScript

81

Solution 1
<html> <head> <SCRIPT> function validateForm(form) { //This is the name of the function if (form.FIELD1.value == "") { //This checks to make sure the field is not empty alert("This field is empty."); //Informs user of empty field form.FIELD1.focus( ); //This focuses the cursor on the empty field return false; //This prevents the form from being submitted } // you may copy the above 5 lines for each form field you wish to validate // Replace the text "FIELD1" with the name you wish to call the field } </SCRIPT> </head> <body> <FORM METHOD="POST" ACTION="" onSubmit="return validateForm(this)"> <INPUT TYPE="TEXT" NAME="FIELD1" SIZE=10 MAXLENGTH=60 VALUE=""> <INPUT TYPE="SUBMIT" NAME="ACTION" value="SUBMIT"> </FORM>

JavaScript

82

Problem

Allow the user to enter two numbers on the screen and show the result of multiplying them

JavaScript

83

Solution
<html> <head> <title>A Simple Calculator</title> <script type="text/javascript"> function multiplyTheFields () { var number_one = document.the_form.field_one.value; var number_two = document.the_form.field_two.value; var product = number_one * number_two;

alert (number_one + " times " + number_two + " is " + product);

</script> </head> <body> <form name = "the_form"> Number 1: <input type = "text" name = "field_one"> <br> Number 2: <input type = "text" name = "field_two"> <br> <a href = "#" onClick = "multiplyTheFields (); return false;">Multiply them! </a> </form> </body> </html>

JavaScript

84

Problem

Modify the above example so that the result of multiplication is not displayed in a separate alert box. Instead, have it displayed in a third text box on the same screen.

JavaScript

85

Solution
<html> <head> <title>A Simple Calculator</title> <script type="text/javascript"> function multiplyTheFields () { var number_one = document.the_form.field_one.value; var number_two = document.the_form.field_two.value; var product = number_one * number_two; document.the_form.the_answer.value = product; } </script> </head> <body> <form name = "the_form"> Number 1: <input type = "text" name = "field_one"> <br> Number 2: <input type = "text" name = "field_two"> <br> The Product: <input type = "text" name = "the_answer"> <br> <a href = "#" onClick = "multiplyTheFields (); return false;">Multiply them! </a> </form> </body> </html>

JavaScript

86

Problem

Create an HTML form and mandate that the user has entered data in all the fields before the form can be submitted.

JavaScript

87

Problem 2

Display a heading and a URL on the screen. When the user moves the mouse over the URL, display a pop up box.

JavaScript

88

Solution 2
<HTML> <TITLE> Example Event Handler </TITLE> <BODY> <H1>Example Event Handler</H1> <P><A HREF = "http://www.test.com" onMouseOver = "alert ('Link to the home page.')">Move the mouse over this link and a popup window appears.</A></P> </BODY> </HTML>
JavaScript 89

Problem 3

In the same example, count and display the number of times the user has moved the mouse over the URL.

JavaScript

90

Solution 3
<HTML> <HEAD> <TITLE> Event Handler with Multiple Statements</TITLE> <SCRIPT LANGUAGE = "JavaScript"> count = 0 </SCRIPT> </HEAD> <BODY> <H1>Event Handler with Multiple Statements</H1> <P><A HREF = "http://www.test.com" onMouseOver = '++count; alert ("Count = "+count+"")'>Displays the count.</A></P> </BODY> </HTML>
JavaScript 91

Problem 4

Display a welcome message when the user views a Web page and also when the user closes the browser window.

JavaScript

92

Solution 4
<HTML> <HEAD> <TITLE> Handling Load Events</TITLE> </HEAD> <BODY onLoad = "alert ('Hello!')" onUnload = "alert ('Bye bye!')"> <H1>Handling load events in a content document</H1> <P>This is a simple document</P> </BODY> </HTML>
JavaScript 93

Problem 5

Accept distance from the user in miles and convert it into kilometers and display the result on the screen.

JavaScript

94

Solution 5
<html> <head> <title>JavaScript Example: Distance Converter</title> </head> <body> <h3>Distance Converter:</h3> <form action="javascript:void();"> <p>Distance in miles: <input name="miles" type="text" size="5"></p> <p> <input type="button" value="Convert to kilometres" onclick= "kilometres = Math.round( form.miles.value * 1.6667 * 100 ) / 100; window.alert( 'Distance in kilometres is ' + kilometres );"> </p> </form> </body> </html>

JavaScript

95

Problem 6

Accept a number from the user and display the result as to whether it is even or odd.

JavaScript

96

Solution 6
<html> <head> <title>Find out if a number is even or odd</title> <script> function EvenOrOdd (num) { if (num.value %2 == 0) return 'Even'; else return 'Odd'; } </script> </head> <body> <h3>Even or odd?</h3> <form action="javascript:void();"> <p>Please enter a number: <input name="num" type="text" size="5"></p> <p> <input type="button" value="Is this even or odd?" onclick= "window.alert ('Number is: ' + EvenOrOdd (num));"> </p> </form> </body> </html>

JavaScript

97

Problem 7

Accept a number from the user and calculate its factorial.

JavaScript

98

Solution 7
<html> <head> <title>Find out the factorial of a number</title> <script language="JavaScript"> function compute(n) { if (validate(n)) { return factorial(n); } else { return "-invalid-"; } } function validate(n) { if (n < 0 || n > 25) { alert("Input must be between 1 and 25."); return false; } else { return true; } } function factorial(n) { var result = 1; for (var i = 2; i <= n; i++) { result *= i } return result; } </script> </head> <body> <H2> Factorial Example </H2> <form name="myForm" method="post" action=""> <p>Enter a number: <input type="text" name="myInput"> <input type="button" name="computeButton" value="Compute!" onclick="with (document.myForm) { result.value=compute(myInput.value) }"> </p>

JavaScript

99

Problem

Have the user enter two numbers on the screen. Swap them if the first is greater than the second.

JavaScript

100

Solution
<html> <head> <script> function swap() { var form=document.switchtext; var t1=form.text1; var v1=parseFloat(t1.value); var t2=form.text2; var v2=parseFloat(t2.value); if (v1 > v2) { var temp = t1.value; t1.value = t2.value; t2.value=temp; } } </script> </head> <body> Please insert only numeric values.<BR /> <form name="switchtext"> <input type="text" name="text1"> <BR /> <input type="text" name="text2"> <BR /> <input type="button" name="switch" value="Switch Text" onclick=swap()> </form> </body> </html>

JavaScript

101

Problem

Ask the user to enter user name and password. The password should be accepted once more for verification. Ensure that the verification is successful.

JavaScript

102

Solution
<html> <head> <!-- Password check --> <script type = "text/javascript"> function validForm(passForm) { if (passForm.passwd1.value == "") { alert("you must enter a password"); passForm.passwd1.focus(); return false; } if (passForm.passwd1.value != passForm.passwd2.value) { alert("Entered passwords did not match"); passForm.passwd1.focus(); passForm.passwd1.select(); return false; } return true; } </script> </head> <body> <form name="form" action="http://www.js-examples.com/" onsubmit="return validForm(this)"> Your name: <input type="text" name="textfield"> <BR> Choose a password: <input type="password" name="passwd1" value="abc123"> <BR> Verify password: <input type="password" name="passwd2" value="abc123"> <BR> <input type="submit" value="Submit"> <input type="reset"> </form> </body> </html>

JavaScript

103

Problem

Create an HTML form to accept first and last names, mailing address, day time phone number, evening time phone number, and email ID of the user. Perform appropriate validations.

JavaScript

104

Solution
<html> <head> <!-- Form validations --> <script language="javascript"> function verify(form) { for (i=0; i<form.elements.length; i++ ) { form.elements[i].focus(); if ((form.elements[i].type=="text" || form.elements[i].type=="textarea") && form.elements[i].value == "") { // having this alert not commented out causes the focus to not work correctly... //alert("Please fill out all fields."); return; } } // if all else is validated - then validiate the email... everify(form); } function everify(form) { if (form.email.value == "" || form.email.value.indexOf('@') == -1 || form.email.value.indexOf('.') == -1 || form.email.value.length<6) { // same for this alert and the focus issue. //alert("Not a valid e-mail address!"); form.email.focus(); return; } // uncomment this to submit the form when all validated. // form.submit(); } </script> </head> <body>

JavaScript

105

HTML Form Elements Illustrated


<html> <body> <form name="everything"> <!-- A one-of-everything HTML form... --> <table border="border" cellpadding="5"> <!-- in a big HTML table --> <tr> <td>Username:<br>[1]<input type="text" name="username" size="15"></td> <td>Password:<br>[2]<input type="password" name="password" size="15"></td> <td rowspan="4">Input Events[3]<br> <textarea name="textarea" rows="20" cols="28"></textarea></td> <td rowspan="4" align="center" valign="center"> [9]<input type="button" value="Clear" name="clearbutton"><br> [10]<input type="submit" name="submitbutton" value="Submit"><br> [11]<input type="reset" name="resetbutton" value="Reset"></td></tr> <tr> <td colspan="2"> Filename: [4]<input type="file" name="file" size="15"></td></tr> <tr> <td>My Computer Peripherals:<br> [5]<input type="checkbox" name="extras" value="burner">DVD Writer<br> [5]<input type="checkbox" name="extras" value="printer">Printer<br> [5]<input type="checkbox" name="extras" value="card">Card Reader</td> <td>My Web Browser:<br> [6]<input type="radio" name="browser" value="ff">Firefox<br> [6]<input type="radio" name="browser" value="ie">Internet Explorer<br> [6]<input type="radio" name="browser" value="other">Other</td></tr> <tr> <td>My Hobbies:[7]<br> <select multiple="multiple" name="hobbies" size="4"> <option value="programming">Hacking JavaScript <option value="surfing">Surfing the Web <option value="caffeine">Drinking Coffee <option value="annoying">Annoying my Friends </select></td> <td align="center" valign="center">My Favorite Color:<br>[8] <select name="color"> <option value="red">Red <option value="green">Green <option value="blue">Blue <option value="white">White <option value="violet">Violet <option value="peach">Peach </select></td></tr> </table>

JavaScript

106

Another Form Validator


<!-- Form validator --> <html> <head> <script type='text/javascript'> function formValidator(){ // Make quick references to our fields var firstname = document.getElementById('firstname'); var addr = document.getElementById('addr'); var zip = document.getElementById('zip'); var state = document.getElementById('state'); var username = document.getElementById('username'); var email = document.getElementById('email'); // Check each input in the order that it appears in the form! if(isAlphabet(firstname, "Please enter only letters for your name")){ if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){ if(isNumeric(zip, "Please enter a valid zip code")){ if(madeSelection(state, "Please Choose a State")){ if(lengthRestriction(username, 6, 8)){ if(emailValidator(email, "Please enter a valid email address")){ return true; } } } } } } return false; } function isEmpty(elem, helperMsg){ if(elem.value.length == 0){ alert(helperMsg);

JavaScript

107

Form Validation Using Another Approach 1


<html> <head>

<SCRIPT TYPE="text/javascript" src=formval.js> </SCRIPT>


<SCRIPT TYPE="text/javascript"> // Only script specific to this form goes here. // General-purpose routines are in a separate file. function validateOnSubmit() { var elem; var errs=0; // execute all element validations in reverse order, so focus gets // set to the first one in error. if (!validateTelnr (document.forms.demo.telnr, 'inf_telnr', true)) errs += 1; if (!validateAge (document.forms.demo.age, 'inf_age', false)) errs += 1; if (!validateEmail (document.forms.demo.email, 'inf_email', true)) errs += 1; if (!validatePresent(document.forms.demo.from, 'inf_from')) errs += 1; if (errs>1) alert('There are fields which need correction before sending'); if (errs==1) alert('There is a field which needs correction before sending'); return (errs==0); }; </SCRIPT> <body> <FORM NAME=demo onsubmit="return validateOnSubmit()" action="dummy.html"> <TABLE CLASS=formtab SUMMARY="Demonstration form"> <TR> <TD STYLE="width: 10em"> <LABEL FOR=from>Your name:</LABEL></TD> <TD><INPUT TYPE=text NAME="from" ID="from" SIZE="35" MAXLENGTH="50" ONCHANGE="validatePresent(this, 'inf_from');"></TD> <TD id="inf_from">Required</TD> </TR> <TR>

JavaScript

108

Form Validation A Case Study

JavaScript

109

Thank you!
Questions and Comments Welcome!

Вам также может понравиться