+ All Categories
Home > Documents > Chapter5 Java Script

Chapter5 Java Script

Date post: 07-Apr-2018
Category:
Upload: piran-faroodi
View: 218 times
Download: 0 times
Share this document with a friend

of 121

Transcript
  • 8/4/2019 Chapter5 Java Script

    1/121

    JAVA SCRIPT

  • 8/4/2019 Chapter5 Java Script

    2/121

    Introduction

    HTML pages are static

    They do not react to events

    There is no programming involved at all Attempts were made to add interactivity to

    HTML pages

    This was done both at client (web browser)side as well as the server side

    Javascript is a client side technology

  • 8/4/2019 Chapter5 Java Script

    3/121

    Basic Concepts

    Earlier there were other technologies like VB

    script and Jscript, however these technologies

    are now obsolete

    Java script is an interpreted language

    It can be directly embedded inside the HTML

    pages or it can be kept in a separate file(with

    file extension js)

    It is supported by all major browsers

  • 8/4/2019 Chapter5 Java Script

    4/121

    Basic Concepts

    Java and Javascript have nothing in common,

    except for naming

  • 8/4/2019 Chapter5 Java Script

    5/121

    Features of Javascript

    JS is a scripting language with a very simple

    syntax

    Can produce dynamic text into an HTML page

    Reacting to events

    Read and write HTML elements

    Validate data

  • 8/4/2019 Chapter5 Java Script

    6/121

    JavaScript Guidelines

    JavaScript is Case Sensitive

    A function named "myfunction" is not the sameas "myFunction" and a variable named "myVar" isnot the same as "myvar".

    White Space

    JavaScript ignores extra spaces. You can addwhite space to your script to make it morereadable. The following lines are equivalent:

    name="Hege";name = "Hege";

  • 8/4/2019 Chapter5 Java Script

    7/121

    JavaScript Guidelines

    Break up a Code Line

    You can break up a code line within a text stringwith a backslash. The example below will bedisplayed properly:

    document.write("Hello \World!");

    However, you cannot break up a code line likethis:

    document.write \("Hello World!");

  • 8/4/2019 Chapter5 Java Script

    8/121

    Javascript example

    document.write(Hello World);

    CLICK TO SEE THE OUTPUT

    http://examples/js%20demo/text_js.htmlhttp://examples/js%20demo/text_js.html
  • 8/4/2019 Chapter5 Java Script

    9/121

    Controlling JS Execution

    Javascript is a part of the HTML page

    Contained inside .. tags

    Document is the name of the object Write is the method of that object

    Writing a script in the head section Executes only when explicitly called

    Writing a script in the body section Executes automatically on its own

  • 8/4/2019 Chapter5 Java Script

    10/121

    JS Example

    JS example in head section

    JS example in body section

    http://examples/js%20demo/head_js.htmlhttp://examples/js%20demo/body_js.htmlhttp://examples/js%20demo/body_js.htmlhttp://examples/js%20demo/head_js.html
  • 8/4/2019 Chapter5 Java Script

    11/121

    External Java Script

  • 8/4/2019 Chapter5 Java Script

    12/121

    Declaring Variables

    Local Variables: variables inside a function

    Global Variables: Variables outside a function

    Example1

    Example2

    http://examples/js%20demo/variable_js.htmlhttp://examples/js%20demo/var_js2.htmlhttp://examples/js%20demo/var_js2.htmlhttp://examples/js%20demo/variable_js.htmlhttp://examples/js%20demo/variable_js.htmlhttp://examples/js%20demo/variable_js.html
  • 8/4/2019 Chapter5 Java Script

    13/121

    Comments in JS

    Single Line Comment

    //

    Multiple Line Comment

    /* .. */

    http://examples/js%20demo/single_comment.htmlhttp://examples/js%20demo/multiple_comment.htmlhttp://examples/js%20demo/multiple_comment.htmlhttp://examples/js%20demo/single_comment.html
  • 8/4/2019 Chapter5 Java Script

    14/121

    HTML in JS

    Example

    http://examples/js%20demo/js_statements.htmlhttp://examples/js%20demo/js_statements.html
  • 8/4/2019 Chapter5 Java Script

    15/121

    Java Script Operators

    Operator

    Classification

    List of Operators

    Arithmetic +, -, *, /, %,++, --

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

    Comparison =,,=,!=

    Logical &&, ||,!

  • 8/4/2019 Chapter5 Java Script

    16/121

    Functions in JS

    All the functions should be defined in the section , right at the beginning of theHTML page

    A function can receive arguments, or it canalso be a function that does not expect anyarguments

    A function is declared using a keyword calledas function followed by the name of thefunction

  • 8/4/2019 Chapter5 Java Script

    17/121

    Functions in JS

    Any arguments expected by the function are

    listed inside the paranthesis, separated by

    commas

    A function can return single value by using the

    return statement

    The function does not have to mention its

    return data type in the function declaration

  • 8/4/2019 Chapter5 Java Script

    18/121

    An example on function

    function total(a,b)

    {

    result=a+b;return result;

    }

  • 8/4/2019 Chapter5 Java Script

    19/121

    Conditional Statements

    If

    If-else

    switch

    http://examples/js%20demo/if_js.htmlhttp://examples/js%20demo/if_else.htmlhttp://examples/js%20demo/switch.htmlhttp://examples/js%20demo/switch.htmlhttp://examples/js%20demo/if_else.htmlhttp://examples/js%20demo/if_else.htmlhttp://examples/js%20demo/if_else.htmlhttp://examples/js%20demo/if_js.html
  • 8/4/2019 Chapter5 Java Script

    20/121

    LOOP

    In JavaScript, there are three 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 do...while Loop

  • 8/4/2019 Chapter5 Java Script

    21/121

    Syntax for FOR LOOP

    for

    (var=startvalue;var

  • 8/4/2019 Chapter5 Java Script

    22/121

    Syntax for WHILE LOOP

    while (var

  • 8/4/2019 Chapter5 Java Script

    23/121

    Syntax for do while loop

    do

    {

    code to be executed

    }while (var

  • 8/4/2019 Chapter5 Java Script

    24/121

    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

    http://examples/js%20demo/break.htmlhttp://examples/js%20demo/break.html
  • 8/4/2019 Chapter5 Java Script

    25/121

    The continue Statement

    The continue statement will break the current

    loop and continue with the next value

    example

    http://examples/js%20demo/continue.htmlhttp://examples/js%20demo/continue.html
  • 8/4/2019 Chapter5 Java Script

    26/121

    JS Pop Up Boxes

    Alert Box

    Alert Box with Line Breaks

    Prompt Box Confirm box

    http://examples/js%20demo/alert_box.htmlhttp://examples/js%20demo/alert_box_linebreaks.htmlhttp://examples/js%20demo/prompt_box.htmlhttp://examples/js%20demo/confirm.htmlhttp://examples/js%20demo/confirm.htmlhttp://examples/js%20demo/prompt_box.htmlhttp://examples/js%20demo/alert_box_linebreaks.htmlhttp://examples/js%20demo/alert_box.html
  • 8/4/2019 Chapter5 Java Script

    27/121

    Events

    By using JavaScript, we have the ability tocreate dynamic web pages. Events are actionsthat can be detected by JavaScript.

    Every element on a web page has certainevents which can trigger a JavaScript. Forexample, we can use the onClick event of abutton element to indicate that a function willrun when a user clicks on the button. Wedefine the events in the HTML tags.

  • 8/4/2019 Chapter5 Java Script

    28/121

    Events

    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 combinationwith functions, and the function will not beexecuted before the event occurs!

  • 8/4/2019 Chapter5 Java Script

    29/121

    onLoad and onUnload

    The onLoad and onUnload events are triggered whenthe user enters or leaves the page.

    The onLoad event is often used to check the visitor'sbrowser 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 auser 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 thenstored in a cookie. Next time the visitor arrives at yourpage, you could have another popup saying somethinglike: "Welcome John Doe!".

  • 8/4/2019 Chapter5 Java Script

    30/121

    What is a Cookie?

    A cookie (also tracking cookie, browsercookie, and HTTP cookie) is a small piece oftext stored on a user's computer by a web

    browser. A cookie consists of one or more name-value

    pairs containing bits of information such asuser preferences, shopping cart contents, theidentifier for a server-based session, or otherdata used by websites.

  • 8/4/2019 Chapter5 Java Script

    31/121

    onFocus, onBlur and onChange

    The onFocus, onBlur and onChange events areoften used in combination with validation of formfields.

    Below is an example of how to use the onChangeevent.

    The checkEmail() function will be calledwhenever the user changes the content of the

    field:

  • 8/4/2019 Chapter5 Java Script

    32/121

    onSubmit

    The onSubmit event is used to validate ALL form fieldsbefore submitting it.

    Below is an example of how to use the onSubmitevent.

    The checkForm() function will be called when the userclicks the submit button in the form.

    The function checkForm() returns either true or false. Ifit returns true the form will be submitted, otherwisethe submit will be cancelled:

  • 8/4/2019 Chapter5 Java Script

    33/121

    onMouseOver and onMouseOut

    onMouseOver and onMouseOut are often usedto create "animated" buttons.

    Below is an example of an onMouseOver event.

    An alert box appears when an onMouseOverevent is detected:

  • 8/4/2019 Chapter5 Java Script

    34/121

    JavaScript Special Characters

    Code Outputs

    \' single quote

    \" double quote

    \& ampersand

    \\ backslash

    \n new line

    \r carriage return

    \t tab

    \b backspace

    \f form feed

  • 8/4/2019 Chapter5 Java Script

    35/121

  • 8/4/2019 Chapter5 Java Script

    36/121

    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.

    An object has properties and methods.

  • 8/4/2019 Chapter5 Java Script

    37/121

    Properties

    Properties are the values associated with an

    object.

    In the following example we are using the

    length property of the String object to return

    the number of characters in a string:

  • 8/4/2019 Chapter5 Java Script

    38/121

    Example of Length Property

    var txt="Hello World!";

    document.write(txt.length);

    The output of the code above will be:

    12

  • 8/4/2019 Chapter5 Java Script

    39/121

    Methods

    Methods are the actions that can be

    performed on objects.

    In the following example we are using the

    toUpperCase() method of the String object to

    display a text in uppercase letters:

  • 8/4/2019 Chapter5 Java Script

    40/121

    Example on Method

    var str="Hello world!";

    document.write(str.toUpperCase());

    The output of the code above willbe:

    HELLO WORLD!

  • 8/4/2019 Chapter5 Java Script

    41/121

    JavaScript String Object

    String Length

    Style Strings

    Index_of

    Match_string

    Replace_string

    http://examples/js%20demo/strlen.htmlhttp://examples/js%20demo/style_strings.htmlhttp://examples/js%20demo/index_of.htmlhttp://examples/js%20demo/match_str.htmlhttp://examples/js%20demo/replace_string.htmlhttp://examples/js%20demo/replace_string.htmlhttp://examples/js%20demo/match_str.htmlhttp://examples/js%20demo/index_of.htmlhttp://examples/js%20demo/style_strings.htmlhttp://examples/js%20demo/strlen.html
  • 8/4/2019 Chapter5 Java Script

    42/121

    Strings

    Concatenating strings (+)

    var a = 'Hello world!';

    var b = 'I am a JavaScript hacker.'

    document.write(a + b);

    Out put

    Hello world!I am a JavaScript hacker.

  • 8/4/2019 Chapter5 Java Script

    43/121

    indexOf

    var a = 'Hello world!';

    document.write(a.indexOf('w'))

    Gives 6

    document.write(a.indexOf('o'))

    gives 4

    document.write(a.indexOf('o',5));

  • 8/4/2019 Chapter5 Java Script

    44/121

    lastIndexOf

    There's also lastIndexOf which gives the last

    occurrence of the character or combination. It

    otherwise works exactly as indexOf. This

    var b = 'I am a JavaScript hacker.'

    document.write(b.lastIndexOf('a'))

    gives 19 because that's the index of the last

    'a' in the string.

  • 8/4/2019 Chapter5 Java Script

    45/121

    charAt

    charAt() gives you the character at a certain

    position. For instance, when you do

    var b = 'I am a JavaScript hacker.'

    document.write(b.charAt(5))

    gives 'a', because that's the character at the

    sixth position (remember, first character is 0!).

  • 8/4/2019 Chapter5 Java Script

    46/121

    split

    split() is a specialized method that you need

    sometimes. It allows you to split a string at the

    places of a certain character. You must put the

    result in an array, not in a simple variable.

    Let's split b on the spaces.

    var b = 'I am a JavaScript hacker.'

    var temp = new Array(); temp = b.split(' ');

  • 8/4/2019 Chapter5 Java Script

    47/121

    output

    Now the string has been split into 5 strings

    that are placed in the array temp. The spaces

    themselves are gone.

    temp[0] = 'I';

    temp[1] = 'am';

    temp[2] = 'a';

    temp[3] = 'JavaScript';

    temp[4] = 'hacker.';

  • 8/4/2019 Chapter5 Java Script

    48/121

    substring

    substring is used to take a part of a string.

    Syntax is substring(first_index,last_index). So

    for instance

    var a = 'Hello world!';

    document.write(a.substring(4,8));

  • 8/4/2019 Chapter5 Java Script

    49/121

    output

    gives 'o wo', from the first 'o' (index 4) to the

    second one (index 7)

    Note that the 'r' (index 8) is notpart of this

    substring.

  • 8/4/2019 Chapter5 Java Script

    50/121

    substring

    var a = 'Hello world!';

    document.write(a.substring(4));

    This gives the whole string from the character

    with index 4 on: 'o world!'.

  • 8/4/2019 Chapter5 Java Script

    51/121

    substr

    There is also a method substr() that works

    slightly differently. Instead of the second

    number being an index number, it gives the

    number of characters. So

    document.write(a.substr(4,8));

  • 8/4/2019 Chapter5 Java Script

    52/121

    output

    starts at the character with index 4 ('o') and

    then gives 8 characters, so the output is

    o world!

  • 8/4/2019 Chapter5 Java Script

    53/121

    toLowerCase and toUpperCase

    var b = 'I am a JavaScript hacker.'

    document.write(b.toUpperCase())

    gives 'I AM A JAVASCRIPT HACKER.'.

  • 8/4/2019 Chapter5 Java Script

    54/121

    Date & Time

    getTime() - Number of milliseconds since1/1/1970 @ 12:00 AM

    getSeconds() - Number of seconds (0-59)

    getMinutes() - Number of minutes (0-59)

    getHours() - Number of hours (0-23)

    getDay() - Day of the week(0-6). 0 = Sunday, ... , 6= Saturday

    getDate() - Day of the month (0-31) getMonth() - Number of month (0-11)

    getFullYear() - The four digit year (1970-9999)

  • 8/4/2019 Chapter5 Java Script

    55/121

    It is now

    var currentTime = new Date() var month =

    currentTime.getMonth() + 1 var day =currentTime.getDate() var year =currentTime.getFullYear()document.write(month + "/" + day + "/" +year)

  • 8/4/2019 Chapter5 Java Script

    56/121

    Instead of displaying the date, display the

    format you might see on a typical digital clock

    -- HH:MM AM/PM (H = Hour, M = Minute).

  • 8/4/2019 Chapter5 Java Script

    57/121

    Code

    var currentTime = new Date()

    var hours = currentTime.getHours()

    var minutes = currentTime.getMinutes() if (minutes < 10){ minutes = "0" + minutes }

    document.write(hours + ":" + minutes + " ")if(hours > 11){ document.write("PM") }

    else { document.write("AM") }

  • 8/4/2019 Chapter5 Java Script

    58/121

    Creating Arrays in JavaScript

    var array_name = new

    Array(number_of_elements)

    array_name[0] = "Array element"

  • 8/4/2019 Chapter5 Java Script

    59/121

    Arrays

    var faq = new Array(3)

    faq[0] = "What are JavaScript arrays"

    faq[1] = "How to create arrays in JavaScript?"

    faq[2] = "What are two dimensional arrays?"

  • 8/4/2019 Chapter5 Java Script

    60/121

    Math Object & Methods

    abs(a) - Returns the absolute value of a

    acos(a) - Returns the angle in radians that hasa cosine of the passed value

    asin(a) - Returns the angle in radians that hasa sine of the passed value

    ceil(x) - Rounds up the value of "a" to the next

    integer floor(a) - Rounds the passed value down to

    the next lowest integer.

  • 8/4/2019 Chapter5 Java Script

    61/121

    Math Methods

    max(a,b) - Returns the larger value of a or b.

    min(a,b) - Returns the lower value of a or b.

    pow(a,b) - Takes the value of a to the power b.

  • 8/4/2019 Chapter5 Java Script

    62/121

    JavaScript Window Object

    The JavaScript Window Object is the highest

    level JavaScript object which corresponds to

    the web browser window

  • 8/4/2019 Chapter5 Java Script

    63/121

    Window object Properties

    clientInformation

    closed - A boolean value that indicates

    whether the window is closed.

    defaultStatus - This is the default message

    that is loaded into the status bar when the

    window loads.

    window.defaultStatus = "Click on a link on the

    left to navigate this website."

  • 8/4/2019 Chapter5 Java Script

    64/121

    Window Object Properties

    status - The status bar is the bar on the lower

    left side of the browser and is used to display

    temporary messages. The below example will

    write a message to the status bar window.status = "This message will display in

    the window status bar."

  • 8/4/2019 Chapter5 Java Script

    65/121

    Example on Window Status

  • 8/4/2019 Chapter5 Java Script

    66/121

    Window Object Methods

    alert("message") - The string passed to the

    alert function is displayed in an alert dialog

    box.

    blur() - This function will take the focus awayfrom the window

    clearInterval(interval) - Clear the timeout

    interval.

  • 8/4/2019 Chapter5 Java Script

    67/121

    Window Object Methods

    close() - This function will close the currentwindow or the named window.

    window.close()

    focus() - This function will give the focus to thewindow.

    moveBy(x,y) - The window is moved the specifiednumber of pixels in the X and Y direction.

    moveTo(x,y) - The window is moved to thespecified X and Y pixel location in the browser.

  • 8/4/2019 Chapter5 Java Script

    68/121

    Window Object Methods

    open("URLname","Windowname",["options"])

    A new window is opened with the namespecified by the second parameter.

    The document specified by the first parameteris loaded.

    The options are not required, and may be set

    to values of yes or no Many options are set to default values

    depending on whether others are set

  • 8/4/2019 Chapter5 Java Script

    69/121

    Open method Options

    For example, if the width and height are specified, theresizable option is set as default to no. Also if thetoolbar is off, the menubar is set to default of no.

    The options are:

    alwaysRaised - If yes, the created window is raised. directories - The value of yes or no determines if the

    window shows directory buttons or not.

    height - Specifies the window height in pixels. This is set toan integer value, rather than yes or no.

    left - Specifies the distance in pixels the new window willbe placed from the left side of the screen. This is set to aninteger value, rather than yes or no.

  • 8/4/2019 Chapter5 Java Script

    70/121

    Open method Options

    location - The value of yes or no determines if the windowhas a location displayed on the address line (or has anaddress line) or not.

    menubar - The value of yes or no determines if thewindow has a menubar or not.

    outerWidth - Specifies the outer window width in pixels.This is set to an integer value, rather than yes or no.

    outerHeight - Specifies the outer window height in pixels.This is set to an integer value, rather than yes or no.

    resizable - The value of yes or no determines if the windowcan be resized by the user or not

  • 8/4/2019 Chapter5 Java Script

    71/121

    Open method Options

    status - The value of yes or no determines if the windowhas a status bar or not.

    scrollbars - The value of yes or no determines if thewindow has scroll bars or not.

    toolbar - The value of yes or no determines if the windowhas a toolbar or not.

    top - Specifies the distance in pixels the new window willbe placed from the top of the screen. This is set to aninteger value, rather than yes or no.

    width - Specifies the window width in pixels. This is set toan integer value, rather than yes or no.

    z-lock - If yes, the created window is in the background.

  • 8/4/2019 Chapter5 Java Script

    72/121

    Example on open method

    Example:

    open("javahere.html","test",

    "toolbar=no,menubar=no,width=200,height=200,resizable=yes")

    example

    http://examples/js%20demo/js_window.htmlhttp://examples/js%20demo/js_window.html
  • 8/4/2019 Chapter5 Java Script

    73/121

    Example on setTimeout

    setTimeout(function(),milliseconds,[functargs]) Used to call a function after the specified time in

    milliseconds.

    If you put the following code in your HTML body start tag:

    And put this code inside your HEAD element:

    function showMessage(){ alert("It has been 4 seconds since this page loaded.") }

    Your page will display the alert message four seconds after

    it loads.

  • 8/4/2019 Chapter5 Java Script

    74/121

    Events

    onafterupdate onBeforeunload

    onBeforeupdate

    onBlur

    onClick

    ondblclick onError

    onerrorupdate

    onFocus

    onhelp

    onkeydown

    onkeypress

  • 8/4/2019 Chapter5 Java Script

    75/121

    Events

    onkeyup onLoad

    onmousedown

    onmousemove

    onmouseout

    onmouseover onmouseup

    onreadystatechange

    onresize

    onrowenter

    onrowexit

    onscroll

    onselectstart

    onUnload

  • 8/4/2019 Chapter5 Java Script

    76/121

    JavaScript History Object

    The JavaScript History Object is property of the

    window object.

    Properties

    current - The current document URL.

    length - The number of entries in the history object.

    next - The URL of the next document in the history

    object.

    previous - The URL of the last document in the history

    object.

  • 8/4/2019 Chapter5 Java Script

    77/121

    History Object Methods: BACK

    Methods

    back() - Go to the previous URL entry in the

    history list. This does the same thing as the

    browser back button.

    The following HTML code creates a back

    button:

  • 8/4/2019 Chapter5 Java Script

    78/121

    History object method: FORWARD

    forward()- Go to the next URL entry in the history list.This does the same thing as the browser forwardbutton.

    This is only effective when there is a next document in

    the history list. The back function or browser back button must have

    previously been used for this function to work.

    The following HTML code creates a forward button:

    b h d

  • 8/4/2019 Chapter5 Java Script

    79/121

    History Object Method: GO

    go(relPos | string) - This function will accept aninteger or a string. If an integer is used, thebrowser will go forward or back (if the value isnegative) the number of specified pages in the

    history object (if the requested entry exists in thehistory object).

    The following example will move the browser

    back one page.

    i bj

  • 8/4/2019 Chapter5 Java Script

    80/121

    JavaScript Form Object

    The JavaScript Form Object is a property of

    the document object.

    This corresponds to an HTML input form

    constructed with the FORM tag.

    A form can be submitted by calling the

    JavaScript submit method or clicking the form

    submit button.

    Obj i

  • 8/4/2019 Chapter5 Java Script

    81/121

    Form Object Properties

    action - This specifies the URL and CGI script file namethe form is to be submitted to. It allows reading orchanging the ACTION attribute of the HTML FORM tag.

    elements - An array of fields and elements in the form.

    encoding - This is a read or write string. It specifies theencoding method the form data is encoded in beforebeing submitted to the server.

    It corresponds to the ENCTYPE attribute of the FORM tag.

    The default is "application/x-www-form-urlencoded". Other encoding includes text/plain or multipart/form-data.

    F Obj P i

  • 8/4/2019 Chapter5 Java Script

    82/121

    Form Object Properties

    length - The number of fields in the elementsarray. I.E. the length of the elements array.

    method - This is a read or write string. It has the

    value "GET" or "POST". name - The form name. Corresponds to the

    FORM Name attribute.

    target - The name of the frame or window theform submission response is sent to by the server.

    Corresponds to the FORM TARGET attribute.

    F Obj B

  • 8/4/2019 Chapter5 Java Script

    83/121

    Form Objects : Buttons

    button - An GUI pushbutton control. Methodsare click(), blur(), and focus(). Attributes:

    name - The name of the button

    type - The object's type. In this case, "button".

    value - The string displayed on the button.

    Ch kb

  • 8/4/2019 Chapter5 Java Script

    84/121

    Checkbox

    checkbox - An GUI check box control. Methods are click(), blur(), and focus().

    Attributes: checked - Indicates whether the checkbox is checked.

    This is a read or write value. defaultChecked - Indicates whether the checkbox is

    checked by default. This is a read only value.

    name - The name of the checkbox.

    type - Type is "checkbox". value - A read or write string that specifies the value

    returned when the checkbox is selected.

    Fil U l d

  • 8/4/2019 Chapter5 Java Script

    85/121

    FileUpload

    FileUpload - This is created with the INPUTtype="file". This is the same as the text element

    with the addition of a directory browser.

    Methods are blur(), and focus(). Attributes: name - The name of the FileUpload object.

    type - Type is "file".

    value - The string entered which is returned when the

    form is submitted.

    example

    Hidd

    http://examples/js%20demo/input_file.htmlhttp://examples/js%20demo/input_file.html
  • 8/4/2019 Chapter5 Java Script

    86/121

    Hidden

    hidden - An object that represents a hiddenform field and is used for client/server

    communications.

    No methods exist for this object. Attributes: name - The name of the Hidden object.

    type - Type is "hidden".

    value - A read or write string that is sent to theserver when the form is submitted.

    P d

  • 8/4/2019 Chapter5 Java Script

    87/121

    Password

    password - A text field used to send sensitivedata to the server.

    Methods are blur(), focus(), and select().

    Attributes: defaultValue - The default value.

    name - The name of the password object."

    type - Type is "password".

    value - A read or write string that is sent to theserver when the form is submitted.

    R di

  • 8/4/2019 Chapter5 Java Script

    88/121

    Radio

    radio - A GUI radio button control. Methods are click(), blur(), and focus().

    Attributes: checked - Indicates whether the radio button is checked.

    This is a read or write value. defaultChecked - Indicates whether the radio button is

    checked by default. This is a read only value.

    length - The number of radio buttons in a group.

    name - The name of the radio button.

    type - Type is "radio". value - A read or write string that specifies the value

    returned when the radio button is selected.

    R t

  • 8/4/2019 Chapter5 Java Script

    89/121

    Reset

    reset - A button object used to reset a formback to default values.

    Methods are click(), blur(), and focus().

    Attributes: name - The name of the reset object.

    type - Type is "reset".

    value - The text that appears on the button. Bydefault it is "reset".

    S l t

  • 8/4/2019 Chapter5 Java Script

    90/121

    Select

    select - A GUI selection list. This is basically a dropdown list.

    Methods are blur(), and focus().

    Attributes:

    length - The number of elements contained in the optionsarray.

    name - The name of the selection list.

    options - An array each of which identifies an options thatmay be selected in the list.

    selectedIndex - Specifies the current selected optionwithin the select list

    type - Type is "select".

    S b it

  • 8/4/2019 Chapter5 Java Script

    91/121

    Submit

    submit - A submit button object.

    Methods are click(), blur(), and focus().

    Attributes:

    name - The name of the submit button.

    type - Type is "submit".

    value - The text that will appear on the button.

    text

  • 8/4/2019 Chapter5 Java Script

    92/121

    text

    text - A GUI text field object.

    Methods are blur(), focus(), and select().

    Attributes:

    defaultValue - The text default value of the text field. name - The name of the text field.

    type - Type is "text".

    value - The text that is entered and appears in the text

    field. It is sent to the server when the form is

    submitted.

    Text Area

  • 8/4/2019 Chapter5 Java Script

    93/121

    Text Area

    textarea - A GUI text area field object. Methods are blur(), focus(), and select().

    Attributes:

    defaultValue - The text default value of the text areafield.

    name - The name of the text area.

    type - Type is textarea.

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

    Form Object Methods

  • 8/4/2019 Chapter5 Java Script

    94/121

    Form Object Methods

    reset() - Used to reset the form elements totheir default values.

    submit() - Submits the form as though the

    submit button were pressed by the user.

    Events

  • 8/4/2019 Chapter5 Java Script

    95/121

    onReset

    onSubmit

    Passing Values to Javascript

  • 8/4/2019 Chapter5 Java Script

    96/121

    Passing Values to Javascript

    function verifyInput(textObject) {

    if (textObject.value == 'CA' || textObject.value == 'AZ') {alert('Nice input')

    }

    else { document.myForm.reset() }}

    Enter CA or AZ:

    Validating radio buttons

  • 8/4/2019 Chapter5 Java Script

    97/121

    Validating radio buttons

    if ( (document.contact_form.gender[0].checked ==

    false ) && (

    document.contact_form.gender[1].checked ==false ) ) { alert ( "Please choose your Gender:

    Male or Female" ); valid = false; }

    Validating drop-down lists

  • 8/4/2019 Chapter5 Java Script

    98/121

    if ( document.contact_form.age.selectedIndex== 0 ) { alert ( "Please select your Age." ); valid

    = false; }

    Validating checkboxes

  • 8/4/2019 Chapter5 Java Script

    99/121

    if ( document.contact_form.terms.checked ==false ) { alert ( "Please check the Terms &

    Conditions box." ); valid = false; }

    JavaScript Navigator Object

  • 8/4/2019 Chapter5 Java Script

    100/121

    JavaScript Navigator Object

    The JavaScript navigator object is the objectrepresentation of the client internet browser

    or web navigator program that is being used.

    This object is the top level object to all others.

    Navigator Properties

  • 8/4/2019 Chapter5 Java Script

    101/121

    Navigator Properties

    appCodeName - The name of the browser's code such as"Mozilla".

    appMinorVersion - The minor version number of thebrowser.

    appName - The name of the browser such as "Microsoft

    Internet Explorer" or "Netscape Navigator". appVersion - The version of the browser which may include

    a compatability value and operating system name.

    cookieEnabled - A boolean value of true or false dependingon whether cookies are enabled in the browser.

    cpuClass - The type of CPU which may be "x86"

    Navigator Properties

  • 8/4/2019 Chapter5 Java Script

    102/121

    Navigator Properties

    mimeTypes - An array of MIME type descriptive strings thatare supported by the browser.

    onLine - A boolean value of true or false.

    platform - A description of the operating system platform.In my case it is "Win32" for Windows 95.

    plugins - An array of plug-ins supported by the browser andinstalled on the browser.

    systemLanguage - The language being used such as "en-us".

    userAgent - In my case it is "Mozilla/4.0 (compatible; MSIE

    4.01; Windows 95)" which describes the browserassociated user agent header.

    userLanguage - The languge the user is using such as "en-us".

    Navigator Methods

  • 8/4/2019 Chapter5 Java Script

    103/121

    Navigator Methods

    javaEnabled() - Returns a boolean telling if thebrowser has JavaScript enabled.

    taintEnabled() - Returns a boolean telling if

    the browser has tainting enabled. Tainting is asecurity protection mechanism for data.

    Multiple Forms in the same Web Page

  • 8/4/2019 Chapter5 Java Script

    104/121

    Multiple Forms in the same Web Page

    Example

    How to Display HTML tags in browser

    http://javascript-forms-example-1/index.htmlhttp://javascript-forms-example-1/index.html
  • 8/4/2019 Chapter5 Java Script

    105/121

    How to Display HTML tags in browser

    There are a few ways to get around this.

    You could put your markup into a textarea

    box.

    You can use an xmp tag.

    Or you could use '& gt;' instead of >.

    example

    http://examples/ex_html.htmlhttp://examples/ex_html.html
  • 8/4/2019 Chapter5 Java Script

    106/121

    Where does Password Encryption

    takes place? Client side or server side

  • 8/4/2019 Chapter5 Java Script

    107/121

    there are two popular approaches ofimplementing encryption

    One, which is done at the client side

    and Two, which is done at the server side (i.e., therequest carries the actual password and at the

    server it's encrypted to be processed further).

    Pictorial Representation of password

  • 8/4/2019 Chapter5 Java Script

    108/121

    authentication scenario works

  • 8/4/2019 Chapter5 Java Script

    109/121

    How can the encryption be

    implemented? Will

    JavaScript/VBScript suffice?

    How good would Applets be?

  • 8/4/2019 Chapter5 Java Script

    110/121

    How good would Applets be?

    They are normally shipped in JAR bundleswhich gives an extra layer of security

    How good is Java Applet?

  • 8/4/2019 Chapter5 Java Script

    111/121

    How good is Java Applet?

    Bytecode tempering is automatically detected: ifan intruder somehow gets hold of the bytecodesand changes that, the changed bytecode willthrow an exception while running

    whereas any such changes in the JavaScript (orVBSCript) source won't be detected.

    Security Mechanism of Java is much moreversatile: the above point is also an integral part

    of the Java Security mechanism, It's quite versatile and layered. No such benefit is

    available with JavaScript (or VBScript).

    How good is Java Applet?

  • 8/4/2019 Chapter5 Java Script

    112/121

    How good is Java Applet?

    JVM offers a far more consistent environment: bytecodes runwithin a Java Virtual Machine which obviously offers a far

    more consistent and stable environment as compared to the

    environment in which JavaScript (or VBSCript) code runs.

    Impl of different public/private keys for every new request:

    you would probably be aware of the Secure Key concept

    which forms a part of the password on many systems. The

    underlying idea in such implementations is to have part of the

    password which keeps on changing on a continuous basis and

    thus making it virtually impossible for the attackers to guessthat. Similarly, if we want to step up the encryption strength

    to an even higher level, we can put in place different

    public/private key combinations for every new request.

    Step 1

  • 8/4/2019 Chapter5 Java Script

    113/121

    Step 1

    #1: typing the Login URL of Online SBI will getyou a web page which will have a JS function

    named encrypt() and an applet named

    encryptApplet. Find below the code-snippetas obtained from the Page Source of the Login

    page:

  • 8/4/2019 Chapter5 Java Script

    114/121

    step2

  • 8/4/2019 Chapter5 Java Script

    115/121

    step2

    #2: Once you enter the password and click 'Login'button, the entered password

    first goes through the basic checks (minimum andmaximum length) and if it passes that then it isencrypted by the applet before it's sent to the web/app

    server. Notice that the public key id is set as it travels to the

    server as a hidden key which is where used foridentifying the corresponding private key id for

    decrypting the password. This makes the web app implement a different

    public/private key combo for every new request.

  • 8/4/2019 Chapter5 Java Script

    116/121

  • 8/4/2019 Chapter5 Java Script

    117/121

    Step 3

  • 8/4/2019 Chapter5 Java Script

    118/121

    Step 3

    #3: see the change in password length before andafter pressing 'Login' button which actually showsthat the encryption is taking place before therequest being sent to the server. Notice that the

    password is encrypted when the 'Login' button isclicked (it turns grey when clicked). Clicking thebutton first performs the basic validations, thenthe password encryption, and finally it submits

    the request to the web/app server.

  • 8/4/2019 Chapter5 Java Script

    119/121

    Step 4

  • 8/4/2019 Chapter5 Java Script

    120/121

    Step 4

    #4: see below a snapshot showing how anexternal JavaScript code looks like whenopened in the browser versus how an appletJAR file opened in browser looks like. EvidentlyJavaScript code is easily visible as it's plaintext. Whereas, opening up the downloadedJAR/Bytecodes will mostly have special

    characters and you got to try hard to get holdof the source, if at all that's possible:

  • 8/4/2019 Chapter5 Java Script

    121/121


Recommended