power point presentation of javascript

Upload: esther-ratna

Post on 07-Apr-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Power Point Presentation of Javascript

    1/110

    JavaScript

    Atul Kahate

    [email protected]

  • 8/3/2019 Power Point Presentation of Javascript

    2/110

    JavaScript 2

    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

  • 8/3/2019 Power Point Presentation of Javascript

    3/110

    JavaScript 3

    Java and JavaScriptAre Java and JavaScript the same?

    NO!

    Java and JavaScript are two completelydifferent languages!

    Java (developed by Sun Microsystems)

    is a powerful and very complexprogramming language - in the samecategory as C and C++

  • 8/3/2019 Power Point Presentation of Javascript

    4/110

    JavaScript 4

    JavaScript Capabilities Programming tool - Scripting language with a very

    simple syntax Dynamic text into an HTML page - Example:

    document.write("" + name + "") Reacting to events - Execute when something

    happens, like when a page has finished loading orwhen 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 willsave the server from extra processing

  • 8/3/2019 Power Point Presentation of Javascript

    5/110

    JavaScript 5

    Simple Example

    document.write("Hello World!")

  • 8/3/2019 Power Point Presentation of Javascript

    6/110

    JavaScript 6

    Example with a Header

    document.write("Hello World!")

  • 8/3/2019 Power Point Presentation of Javascript

    7/110

    JavaScript 7

    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 auser triggers an event

  • 8/3/2019 Power Point Presentation of Javascript

    8/110

    JavaScript 8

    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 inthe head section

    When we place a script in the head

    section, we will ensure that the script isloaded before anyone uses it

  • 8/3/2019 Power Point Presentation of Javascript

    9/110

    JavaScript 9

    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

  • 8/3/2019 Power Point Presentation of Javascript

    10/110

    JavaScript 10

    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 havescripts in both the body and the headsection.

  • 8/3/2019 Power Point Presentation of Javascript

    11/110

    JavaScript 11

    External JavaScript

  • 8/3/2019 Power Point Presentation of Javascript

    12/110

    JavaScript 12

    Script in the head elementfunction message()

    {alert("This alert box was called with the onload event")}

  • 8/3/2019 Power Point Presentation of Javascript

    13/110

    JavaScript 13

    Script in the Body Element

    document.write("This message is written when the page loads")

  • 8/3/2019 Power Point Presentation of Javascript

    14/110

    JavaScript 14

    JavaScript Variables Rules for Variable names:

    Variable names are case sensitive They must begin with a letter or the underscore

    character Syntaxes

    var strname = some value strname = some value

    Examples var strname = Ram" strname = Ram"

  • 8/3/2019 Power Point Presentation of Javascript

    15/110

    JavaScript 15

    Variables Scope Local variables

    When you declare a variable within a function, thevariable can only be accessed within that function

    When you exit the function, the variable isdestroyed

    Global variables If you declare a variable outside a function, all the

    functions on your page can access it

    The lifetime of these variables starts when theyare declared, and ends when the page is closed

  • 8/3/2019 Power Point Presentation of Javascript

    16/110

    JavaScript 16

    JavaScript Operators

    Arithmetic + - * / % ++ --

    Assignment = += -= *= /= %=

    Comparison == != < > =

    Logical && || !

    String joining

  • 8/3/2019 Power Point Presentation of Javascript

    17/110

    JavaScript 17

    JavaScript Functions

    A function contains some code that will be executedby an event or a call to that function

    A function is a set of statements

    You can reuse functions within the same script, or inother documents

    You define functions at the beginning of a file (in thehead section), and call them later in the document

    Example alert("This is a message")

  • 8/3/2019 Power Point Presentation of Javascript

    18/110

    JavaScript 18

    Function Syntaxes

    Function with argumentsfunction myfunction(argument1,argument2,etc){

    some statements}

    Function without argumentsfunction myfunction(){

    some statements}

    A function can return a value by using the returnstatement

  • 8/3/2019 Power Point Presentation of Javascript

    19/110

    JavaScript 19

    Example of a Function Call

    function total(a,b)

    {

    result=a+b

    return result

    }

    sum=total(2,3)

  • 8/3/2019 Power Point Presentation of Javascript

    20/110

    JavaScript 20

    JavaScript ConditionalStatements

    if statement - use this statement if youwant 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 toexecute

    switch statement - use this statement ifyou want to select one of many sets of linesto execute

  • 8/3/2019 Power Point Presentation of Javascript

    21/110

    JavaScript 21

    if Example

    //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

  • 8/3/2019 Power Point Presentation of Javascript

    22/110

    JavaScript 22

    if-else Example

    //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!")}

  • 8/3/2019 Power Point Presentation of Javascript

    23/110

    Statements, II The switch statement:

    switch (expression) {case label:statement;

    break;case label:statement;break;

    ...default : statement;

    }

  • 8/3/2019 Power Point Presentation of Javascript

    24/110

    Other familiar statements: break;

    continue;

    The empty statement, as in ;; or { }

  • 8/3/2019 Power Point Presentation of Javascript

    25/110

    JavaScript 25

    switch Example//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!")

    }

  • 8/3/2019 Power Point Presentation of Javascript

    26/110

    JavaScript 26

    Conditional Operator

    Syntax

    variablename=(condition)?value1:value2

    Example

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

  • 8/3/2019 Power Point Presentation of Javascript

    27/110

    JavaScript 27

    JavaScript Loops

    while - loops through a block of codewhile a condition is true

    do...while - loops through a block ofcode once, and then repeats the loopwhile a condition is true

    for - run statements a specified numberof times

  • 8/3/2019 Power Point Presentation of Javascript

    28/110

    JavaScript 28

    for Examplehtml>

    for (i = 0; i

  • 8/3/2019 Power Point Presentation of Javascript

    29/110

    JavaScript 29

    while Example

    i = 0while (i

  • 8/3/2019 Power Point Presentation of Javascript

    30/110

    JavaScript 30

    do-while Example

    i = 0do

    {document.write("The number is " + i)document.write("
    ")i++}while (i

  • 8/3/2019 Power Point Presentation of Javascript

    31/110

    JavaScript 31

    JavaScript Objects

    Array

    Boolean

    Date

    Math

    String

  • 8/3/2019 Power Point Presentation of Javascript

    32/110

    JavaScript 32

    Arrays

    Syntax

    var family_names=new Array(3) OR

    var family_names=newArray("Tove","Jani","Stale")

    Accesing array elements

    family_names[0]="Tove"family_names[1]="Jani"family_names[2]="Stale"

  • 8/3/2019 Power Point Presentation of Javascript

    33/110

    JavaScript 33

    Some of the Array MethodsMethod Description

    concat() Joins two or more arrays and returns anew array

    reverse() Reverses the order of the elements inan array

    shift() Removes and returns the first elementof an array

    slice(begin[,end]) Creates a new array from a selected

    section of an existing arraysort() Sorts the elements of an array

  • 8/3/2019 Power Point Presentation of Javascript

    34/110

    JavaScript 34

    Boolean Object

    The Boolean object is an object wrapper for a Boolean valueand it is used to convert a non-Boolean value to a Boolean value

    Example: Initialize to null var b1=new Boolean() var b2=new Boolean(0) var b3=new Boolean(null) var b4=new Boolean("") var b5=new Boolean(false)

    Example: Initialize to a non-null value var b1=new Boolean(true) var b2=new Boolean("true") var b3=new Boolean("false") var b4=new Boolean("Richard")

  • 8/3/2019 Power Point Presentation of Javascript

    35/110

    JavaScript 35

    Date Object 1

    Get todays date

    var d = new Date()document.write(d.getDate())document.write(".")document.write(d.getMonth() + 1)document.write(".")

    document.write(d.getFullYear())

  • 8/3/2019 Power Point Presentation of Javascript

    36/110

    JavaScript 36

    Date Object 2

    Set year, month, day values

    var d = new Date()d.setFullYear("1990")document.write(d)

  • 8/3/2019 Power Point Presentation of Javascript

    37/110

    JavaScript 37

    Date Object 3

    Display the day of the week (Sunday, )

    var d=new Date()var weekday=new

    Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")

    document.write("Today is " + weekday[d.getDay()])

  • 8/3/2019 Power Point Presentation of Javascript

    38/110

    JavaScript 38

    Date Object 4

    Display date in the format Tuesday 7 Dec 2004

    var d=new Date()var weekday=new

    Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")

    var monthname=newArray("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())

  • 8/3/2019 Power Point Presentation of Javascript

    39/110

    JavaScript 39

    Summary of Date Functions

    Method Description

    Date() Returns a Date object

    getDate() Returns the date of a Date object (from 1-31)

    getDay() Returns the day of a Date object (from 0-6. 0=Sunday, 1=Monday,etc.)

    getMonth() Returns the month of a Date object (from 0-11. 0=January,1=February, etc.)

    getFullYear() Returns the year of a Date object (four digits)

    getYear() Returns the year of a Date object (from 0-99). Use getFullYear instead

    getHours() Returns the hour of a Date object (from 0-23)

    getMinutes() Returns the minute of a Date object (from 0-59)

    getSeconds() Returns the second of a Date object (from 0-59)

  • 8/3/2019 Power Point Presentation of Javascript

    40/110

    JavaScript 40

    JavaScript Math Object

    The built-in Math object includesmathematical constants and functions

    We do not need to create the Mathobject before using it

    Example

    r_number=Math.round(8.6)

    r_number=Math.random()

  • 8/3/2019 Power Point Presentation of Javascript

    41/110

    JavaScript 41

    Math Example 1

    document.write(Math.round(7.25))

  • 8/3/2019 Power Point Presentation of Javascript

    42/110

    JavaScript 42

    Math Example 2

    document.write(Math.max(2,4))

  • 8/3/2019 Power Point Presentation of Javascript

    43/110

    JavaScript 43

    Math Object Methods

    Method Description

    abs(x) Returns the absolute value of x

    cos(x) Returns the cosine of x

    exp(x) Returns the value of E raised to the power of xlog(x) Returns the natural log of x

    max(x,y) Returns the number with the highest value of x and y

    min(x,y) Returns the number with the lowest value of x and y

    pow(x,y) Returns the value of the number x raised to the power of y

    random() Returns a random number between 0 and 1round(x) Rounds x to the nearest integer

    sin(x) Returns the sine of x

    sqrt(x) Returns the square root of x

    tan(x) Returns the tangent of x

  • 8/3/2019 Power Point Presentation of Javascript

    44/110

    JavaScript 44

    JavaScript String Object

    Method Description

    bold() Returns a string in bold

    charAt(index) Returns the character at a specified position

    concat() Returns two concatenated strings

    italics() Returns a string in italic

    replace() Replaces some specified characters with some new specified characters

    search() Returns an integer if the string contains some specified characters, if not it returns -1

    substr() Returns the specified characters. 14,7 returns 7 characters, from the 14th character (startsat 0)

    substring() Returns the specified characters. 7,14 returns all characters from the 7th up to but notincluding the 14th (starts at 0)

    toLowerCase() Converts a string to lower case

    toUpperCase() Converts a string to upper case

  • 8/3/2019 Power Point Presentation of Javascript

    45/110

    JavaScript 45

    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 /* */

  • 8/3/2019 Power Point Presentation of Javascript

    46/110

    HTML DOM

  • 8/3/2019 Power Point Presentation of Javascript

    47/110

    JavaScript 47

    What is HTML DOM?

    The HTML DOM is a programming interfacefor HTML documents

    The HTML DOM defines how you can accessand change the content of HTML documents

    DOM stands for the Document Object Model

    The HTML DOM defines a standard set ofobjects for HTML, and a standard way toaccess and manipulate HTML objects

  • 8/3/2019 Power Point Presentation of Javascript

    48/110

    JavaScript 48

    Why HTML DOM?

    Because we need an easy and standard wayto 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 accesscontents of HTML documents

    The HTML DOM defines how to access HTMLelements, and how to change, add, or deletetheir content, attributes and styles

  • 8/3/2019 Power Point Presentation of Javascript

    49/110

    JavaScript 49

    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

  • 8/3/2019 Power Point Presentation of Javascript

    50/110

    JavaScript 50

    DOM Example

    function ChangeColor(){document.body.bgColor="yellow"}

    Click on this document!

    Result: After the document is displayed in the browser window; if the user clicks in the browser,the background color would change to yellow.

  • 8/3/2019 Power Point Presentation of Javascript

    51/110

    JavaScript 51

    Document Objects

    DOM views an HTML document as acollection of objects

    Sample objects Document object is the parent of all the other

    objects in an HTML document

    Document.body object represents the element of the HTML document

    Meaning: Document object is the parent of thebody object, and the body object is a child of thedocument object.

  • 8/3/2019 Power Point Presentation of Javascript

    52/110

    JavaScript 52

    Object Properties/Attributes

    HTML document objects can have properties(also called attributes)

    e.g. document.body.bgColor property definesthe background color of the body object.

    The statementdocument.body.bgColor="yellow sets the

    background color of the HTML document toyellow

  • 8/3/2019 Power Point Presentation of Javascript

    53/110

    JavaScript 53

    Object Events

    HTML document objects can respond toevents

    The onclick="ChangeColor()" defines anaction to take place when the userclicks on the document

  • 8/3/2019 Power Point Presentation of Javascript

    54/110

    JavaScript 54

    Important Objects from DOMSet

  • 8/3/2019 Power Point Presentation of Javascript

    55/110

    JavaScript 55

    Button Object

    The button object represents a push buttonon an HTML form

    For each instance of an HTML tag on an HTML form, aButton object is created

    The Button objects are stored in the elementsarray of the corresponding form

    We can access a Button object by indexingthis array - either by number (0 representsthe first element in a form) or by using thevalue of the name attribute

  • 8/3/2019 Power Point Presentation of Javascript

    56/110

    JavaScript 56

    Button Examplefunction show_alert(){alert("Hello World!")document.all("myButton").focus()}

  • 8/3/2019 Power Point Presentation of Javascript

    57/110

    JavaScript 57

    Checkbox Object

    The Checkbox object represents a checkboxon an HTML form

    For each instance of an HTML tag on an HTML form, aCheckbox object is created

    All Checkbox objects are stored in theelements array of the corresponding form

    We can access a Checkbox object by indexingthis array - either by number (0 representsthe first element in a form) or by using thevalue of the name attribute

    Ch kb E l

  • 8/3/2019 Power Point Presentation of Javascript

    58/110

    JavaScript 58

    Checkbox Example

    function check(){coffee=document.forms[0].coffeeanswer=document.forms[0].answertxt=""for (i=0;i

  • 8/3/2019 Power Point Presentation of Javascript

    59/110

    JavaScript 59

    Document Object

    The Document object is used to accessall elements in a page

    Contains many collections, properties,methods, and events

    No example for this

  • 8/3/2019 Power Point Presentation of Javascript

    60/110

    JavaScript 60

    Event Object

    Represents the state of an event, such as theelement in which the event occurred, thestate of the keyboard keys, the location of

    the mouse, and the state of the mousebuttons

    Is available only during an event - that is, youcan use it in event handlers but not in other

    code In VBScript, you must access the event object

    through the window object

  • 8/3/2019 Power Point Presentation of Javascript

    61/110

    JavaScript 61

    Event Example 1function whichButton(){

    if (event.button==1)alert("You clicked the left mouse button!")else

    alert("You clicked the right mouse button!")}

    Click in the document. An alert box will alert which mouse button you

    clicked.

  • 8/3/2019 Power Point Presentation of Javascript

    62/110

    JavaScript 62

    Event Example 2

    function isKeyPressed(){if (event.shiftKey==1)

    alert("The shift key was pressed!")else

    alert("The shift key was NOT pressed!")}

    Click somewhere in the document. An alert box will tell you if you pressed the shift key ornot.

  • 8/3/2019 Power Point Presentation of Javascript

    63/110

    JavaScript 63

    Form Object

    Forms are used to prompt users forinput

    We may use form elements such as textfields, radio buttons, checkboxes andselection lists

    The input data is normally posted to aserver for processing

  • 8/3/2019 Power Point Presentation of Javascript

    64/110

    JavaScript 64

    Form Example

    function formSubmit(){document.forms.myForm.submit()}

    Firstname:
    Lastname:

  • 8/3/2019 Power Point Presentation of Javascript

    65/110

    JavaScript 65

    Forms Example with Inputs

    Type your first name:
    Type your last name:

  • 8/3/2019 Power Point Presentation of Javascript

    66/110

    JavaScript 66

    Form Example 1 (Page 1 of 3)

    function validate()

    {x=document.myFormat=x.email.value.indexOf("@")code=x.code.valuefirstname=x.fname.valuesubmitOK="True"

    if (at==-1){alert("Not a valid e-mail!")submitOK="False"}

  • 8/3/2019 Power Point Presentation of Javascript

    67/110

    JavaScript 67

    Form Example 1 (Page 2 of 3)

    if (code5){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}

    }

  • 8/3/2019 Power Point Presentation of Javascript

    68/110

    JavaScript 68

    Form Example 1 (Page 3 of 3)

    Enter your e-mail:
    Enter a value from 1 to 5:

    Enter your name, max 10 chararcters:

    Form Example 2

  • 8/3/2019 Power Point Presentation of Javascript

    69/110

    JavaScript 69

    Form Example 2

    function check(browser){document.forms[0].answer.value=browser}

    Select which browser is your favorite:

    Internet Explorer
    Netscape
    Opera


  • 8/3/2019 Power Point Presentation of Javascript

    70/110

    JavaScript 70

    Option Object 1

    For each instance of an HTML tagin a selection list on a form, an Option objectis created

    An option in a selection list can be createdeither with the HTML tag Wolksvagen OR

    Using the option constructor and assign it toan index of the relevant Select object document.myForm.cartypes[3]=new

    Option("Wolksvagen")

  • 8/3/2019 Power Point Presentation of Javascript

    71/110

    JavaScript 71

    Option Object 2

    To specify a value to be returned to theserver 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")

    Option E ample 1

  • 8/3/2019 Power Point Presentation of Javascript

    72/110

    JavaScript 72

    Option Example - 1function makeDisable()

    {var x=document.getElementById("mySelect")x.disabled=true}function makeEnable(){var x=document.getElementById("mySelect")x.disabled=false}

    AppleGrapeOrange

    document.forms[0].mySelect[3]=new Option("Mango")

    Option Example 2

  • 8/3/2019 Power Point Presentation of Javascript

    73/110

    JavaScript 73

    Option Example - 2

    function getText(){var x=document.getElementById("mySelect")alert(x.options[x.selectedIndex].text)}

    Select your favorite fruit:

    AppleOrangePineapple

    Banana

    Option Example 3

  • 8/3/2019 Power Point Presentation of Javascript

    74/110

    JavaScript 74

    Option Example - 3html>

    function getIndex(){var x=document.getElementById("mySelect")alert(x.options[x.selectedIndex].index)}

    Select your favorite fruit:

    AppleOrangePineapple

    Banana

    Option Example 4

  • 8/3/2019 Power Point Presentation of Javascript

    75/110

    JavaScript 75

    Option Example - 4

    function changeText(){var x=document.getElementById("mySelect")x.options[x.selectedIndex].text="Melon"}

    Select your favorite fruit:

    AppleOrangePineapple

    Banana

    Option Example 5

  • 8/3/2019 Power Point Presentation of Javascript

    76/110

    JavaScript 76

    Option Example - 5

    function changeText(){var x=document.getElementById("mySelect")x.options[x.selectedIndex].text="Melon"}

    Select your favorite fruit:

    AppleOrangePineapple

    Banana

  • 8/3/2019 Power Point Presentation of Javascript

    77/110

    JavaScript 77

    Pop up boxes

    Three types Alert Box

    Syntax: alert (Your message)

    A pop-up screen appears User needs to select OK to proceed

    Confirm Box Syntax: confirm (Your message)

    User needs to select OK or Cancel

    Prompt Box User needs to type something and then select OK or

    Cancel

  • 8/3/2019 Power Point Presentation of Javascript

    78/110

    JavaScript 78

    Alert Box Example

    alert("Please acknowledge this first!"); Test page Hello world!

  • 8/3/2019 Power Point Presentation of Javascript

    79/110

    JavaScript 79

    Confirm Box Example

    if (confirm("Do you agree"))

    {alert("You agree")}else

    {alert ("You do not agree")};

    My shop Good bye!

  • 8/3/2019 Power Point Presentation of Javascript

    80/110

    JavaScript 80

    Exercises

  • 8/3/2019 Power Point Presentation of Javascript

    81/110

    JavaScript 81

    Problem 1

    Requirement: Allow the user to entersome text in a textbox and validate to

    ensure that it is not empty.

  • 8/3/2019 Power Point Presentation of Javascript

    82/110

    JavaScript 82

    Solution 1

    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 fieldform.FIELD1.focus( ); //This focuses the cursor on the empty fieldreturn 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}

  • 8/3/2019 Power Point Presentation of Javascript

    83/110

    JavaScript 83

    Problem

    Allow the user to enter two numbers onthe screen and show the result of

    multiplying them

  • 8/3/2019 Power Point Presentation of Javascript

    84/110

    JavaScript 84

    Solution

    A Simple Calculator

    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);}

    Number 1:
    Number 2:
    Multiply them!

  • 8/3/2019 Power Point Presentation of Javascript

    85/110

    JavaScript 85

    Problem

    Modify the above example so that theresult of multiplication is not displayed

    in a separate alert box. Instead, have itdisplayed in a third text box on thesame screen.

  • 8/3/2019 Power Point Presentation of Javascript

    86/110

    JavaScript 86

    Solution

    A Simple Calculator

    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;

    }

    Number 1:

    Number 2:
    The Product:
    Multiply them!

  • 8/3/2019 Power Point Presentation of Javascript

    87/110

    JavaScript 87

    Problem

    Create an HTML form and mandate thatthe user has entered data in all the

    fields before the form can be submitted.

  • 8/3/2019 Power Point Presentation of Javascript

    88/110

    JavaScript 88

    Problem 2

    Display a heading and a URL on thescreen. When the user moves the

    mouse over the URL, display a pop upbox.

  • 8/3/2019 Power Point Presentation of Javascript

    89/110

    JavaScript 89

    Solution 2

    Example Event Handler

    Example Event Handler

    Move the mouse over this link and a

    popup window appears.

  • 8/3/2019 Power Point Presentation of Javascript

    90/110

    JavaScript 90

    Problem 3

    In the same example, count and displaythe number of times the user has

    moved the mouse over the URL.

  • 8/3/2019 Power Point Presentation of Javascript

    91/110

    JavaScript 91

    Solution 3

    Event Handler with Multiple Statements

    count = 0Event Handler with Multiple Statements

    Displays the count.

  • 8/3/2019 Power Point Presentation of Javascript

    92/110

    JavaScript 92

    Problem 4

    Display a welcome message when theuser views a Web page and also when

    the user closes the browser window.

  • 8/3/2019 Power Point Presentation of Javascript

    93/110

    JavaScript 93

    Solution 4

    Handling Load Events

    Handling load events in a contentdocument

    This is a simple document

  • 8/3/2019 Power Point Presentation of Javascript

    94/110

    JavaScript 94

    Problem 5

    Accept distance from the user in milesand convert it into kilometers and

    display the result on the screen.

  • 8/3/2019 Power Point Presentation of Javascript

    95/110

    JavaScript 95

    Solution 5

    JavaScript Example: Distance Converter

    Distance Converter:

    Distance in miles:

  • 8/3/2019 Power Point Presentation of Javascript

    96/110

    JavaScript 96

    Problem 6

    Accept a number from the user anddisplay the result as to whether it is

    even or odd.

  • 8/3/2019 Power Point Presentation of Javascript

    97/110

    JavaScript 97

    Solution 6

    Find out if a number is even or odd

    function EvenOrOdd (num){

    if (num.value %2 == 0)

    return 'Even';elsereturn 'Odd';

    }

    Even or odd?

    Please enter a number:

  • 8/3/2019 Power Point Presentation of Javascript

    98/110

    JavaScript 98

    Problem 7

    Accept a number from the user andcalculate its factorial.

  • 8/3/2019 Power Point Presentation of Javascript

    99/110

    JavaScript 99

    Solution 7

    Find out the factorial of a numberfunction 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

  • 8/3/2019 Power Point Presentation of Javascript

    100/110

    JavaScript 100

    Problem

    Have the user enter two numbers onthe screen. Swap them if the first is

    greater than the second.

  • 8/3/2019 Power Point Presentation of Javascript

    101/110

    JavaScript 101

    Solution

    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;

    }}

    Please insert only numeric values.


  • 8/3/2019 Power Point Presentation of Javascript

    102/110

    JavaScript 102

    Problem

    Ask the user to enter user name andpassword. The password should be

    accepted once more for verification.Ensure that the verification issuccessful.

  • 8/3/2019 Power Point Presentation of Javascript

    103/110

    JavaScript 103

    Solution

    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;

    }

    Your name:
    Choose a password:

    Verify password:

  • 8/3/2019 Power Point Presentation of Javascript

    104/110

    JavaScript 104

    Problem

    Create an HTML form to accept first andlast names, mailing address, day time

    phone number, evening time phonenumber, and email ID of the user.Perform appropriate validations.

  • 8/3/2019 Power Point Presentation of Javascript

    105/110

    JavaScript 105

    Solution

    function verify(form) {

    for (i=0; i

  • 8/3/2019 Power Point Presentation of Javascript

    106/110

    JavaScript 106

    Illustrated

    Username:
    [1]Password:
    [2]Input Events[3]

    [9]

    [10]
    [11]

    Filename: [4]My Computer Peripherals:

    [5]DVD Writer
    [5]Printer
    [5]Card Reader

    My Web Browser:
    [6]Firefox
    [6]Internet Explorer
    [6]Other

    My Hobbies:[7]

    Hacking JavaScriptSurfing the WebDrinking CoffeeAnnoying my Friends

    My Favorite Color:
    [8]

    Red GreenBlue WhiteViolet Peach

  • 8/3/2019 Power Point Presentation of Javascript

    107/110

    JavaScript 107

    Another Form Validator

    function formValidator(){// Make quick references to our fieldsvar 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);

    Form Validation Using Another

  • 8/3/2019 Power Point Presentation of Javascript

    108/110

    JavaScript 108

    gApproach 1

    // 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);};

    Your name:Required

    Form Validation A Case

  • 8/3/2019 Power Point Presentation of Javascript

    109/110

    JavaScript 109

    Study

  • 8/3/2019 Power Point Presentation of Javascript

    110/110

    Thank you!

    Questions and Comments Welcome!