JavaScript - PowerPoint PPT Presentation

1 / 142
About This Presentation
Title:

JavaScript

Description:

JavaScript CS 268 * An input receives the focus when a user clicks it or tabs to it. It looses the focus then the user clicks a different input or tabs away from it ... – PowerPoint PPT presentation

Number of Views:308
Avg rating:3.0/5.0
Slides: 143
Provided by: Joli52
Category:

less

Transcript and Presenter's Notes

Title: JavaScript


1
JavaScript
  • CS 268

2
Topics
  • Introduction to JavaScript
  • Positioning a script
  • Variables
  • Type conversions
  • Concatenation
  • HTML forms
  • Document Object Model
  • Functions
  • Form Validation
  • Debugging
  • Stuff...

3
What is JavaScript all about?
  • Small program
  • Runs in the client browser
  • Typical uses
  • Perform simple calculations on existing Web page
    data
  • Perform error checking on user inputs in HTML
    form elements
  • Manipulate data that the developer embeds in the
    HTML document
  • Create and read cookies
  • Control the appearance of the current Web

4
How a Script Works
  • Scripts are interpreted
  • Source code translated to machine language one
    line at a time each time script is run
  • Actually it's more complicated than that
    browsers today have hybrid JavaScript
    implementations that compile some of the code and
    where required interpret some of it.
  • Can write with any text editor
  • But it's a "lot" easier if the editor provides
    color coding and code completion support!

5
JavaScript and Object Oriented Programming
  • JavaScript supports OO programming including
    inheritance
  • We aren't going to cover this
  • It also supports try/catch error handling
  • But with code to detect user entry errors this
    shouldn't be needed
  • You can learn more about JavaScript OO from the
    following two links (not required for this class)

http//www.javascriptkit.com/javatutors/oopjs.shtm
l
http//www.crockford.com/javascript/inheritance.ht
ml
6
Adding Javascript to a Web Page
  • Add the script tag anywhere in the Web page body
  • Place the tag where you want the script to
    execute
  • Add the script commands within the script tags
  • ltscript language"JavaScript" type"text/javascri
    pt"gt
  • first script command
  • second script command
  • lt/scriptgt
  • Shortening the initial script tag to this is
    acceptable and recommended
  • ltscriptgt

Browsers default to language"JavaScript"
typetext/javascript if you omit these attributes
http//www.javascriptkit.com/javatutors/languageat
tri.shtml
7
Topics
  • Introduction to JavaScript
  • Positioning a script
  • Variables
  • Type conversions
  • Concatenation
  • HTML forms
  • Document Object Model
  • Functions
  • Form Validation
  • Debugging
  • Stuff...

8
When does the script execute?
  • If commands are not contained within a function,
    they execute in sequence as the page is loaded
    into the browser
  • If contained within a function the commands do
    not execute until explicitly called by clicking a
    button (or other event)

9
Where can you place a script?
  • This is okay where it is normally placed if
    written in the html file (most other locations
    also work)
  • lthtmlgt
  • ltheadgt
  • ltscriptgt
  • alert("Hello")
  • lt/scriptgt
  • lttitlegtHello Page Titlelt/titlegt
  • lt/headgt
  • Dont do this (you can come up with other places
    it won't work)
  • lthtmlgtltheadgt
  • lttitlegtHello Page Title
  • ltscriptgt
  • alert("Hello")
  • lt/scriptgt
  • lt/titlegt

10
What will the alert display when this script runs?
  • A The alert will display
  • Last name is Smith
  • B The alert will display
  • Last name is
  • C The alert won't be displayed
  • D No idea

11
Affects of script location
  • Cant access a page object until it has loaded.
    For example this wont work
  • ltscriptgt
  • alert("The default employee last name is "
  • document.frmEmployee.txtLastname.value)
  • lt/scriptgt
  • ltform name"frmEmployee"gt
  • lt!-- initialize the last name to Smith --gt
  • ltinput name"txtLastname" value"Smith"gt
  • lt/formgt
  • But this will work
  • ltform name"frmEmployee"gt
  • lt!-- initialize the last name to Smith --gt
  • ltinput name"txtLastname" value"Smith"gt
  • lt/formgt
  • ltscriptgt
  • alert("The default employee last name is "
  • document.frmEmployee.txtLastname.value)
  • lt/scriptgt

12
Topics
  • Introduction to JavaScript
  • Positioning a script
  • Variables
  • Type conversions
  • Concatenation
  • HTML forms
  • Document Object Model
  • Functions
  • Form Validation
  • Debugging
  • Stuff...

13
JavaScript Data Types
  • JavaScript is a loosely-typed language
  • You don't declare the data type when you declare
    the variable
  • The variable assumes the "correct" data type when
    you assign a value to it
  • The language "usually" converts a variable value
    to the correct data type when you perform
    operations on it

14
Data Types
  • JavaScript types
  • Boolean (true, false)
  • Number (10, -3.31)
  • Object (document.frmForm1.txtInput)
  • String ("Now is the time")
  • Date (12/4/2009)
  • Data Types? The previous slide said it is
    "loosely typed"

15
Data Types
  • JavaScript variables assume the data type of
    whatever is assigned to them
  • var name "Hello"
  • name is a string
  • var whatever 12
  • whatever is a number
  • var whatever "Something"
  • whatever is a string

16
Using var to declare variables
  • Don't have to use var
  • But if you don't you can get some unexpected
    behavior I'll show this in class

Use var to get the usual (like Java) scoping of
variables!
17
Using var to declare variables
  • Improved

Try catch another possibility (but the upper
solution is better)
18
What happens now when the user assigns a name and
then tries to display it?
19
JavaScript Objects
  • Variables (and constants) are also Objects
  • Objects can do more than store a value
  • Examples of object operations
  • String
  • determine length of string
  • convert to upper/lowercase letters
  • Number
  • convert to fixed number of places after the
    decimal point
  • Date
  • finding the current date/time from the system
    clock

20
Example of String Object Properties Methods
Property or Method Description Example Result
length Returns the length of a text string var myString new String() myString "Joline" var strLength myString.length 6
toLowerCase Converts a string to lowercase letters var myString new String() myString "Joline" var strLowerCase myString.toLowerCase() "joline"
toUpperCase Converts a string to uppercase letters var myString new String() myString "Joline" var strUpperCase myString.toUpperCase() "JOLINE"
21
Example of Number Object Properties Methods
Property or Method Description Example Result
toFixed Rounds a number to a specified number of decimal places var myNumber 3.14157 var myRoundedNumber myNumber.toFixed(3) 3.142
22
Example of Date Object Properties Methods
Property or Method Description Example
getFullYear() Returns the current four-digit year var myDate new Date() var CurrentYear myDate.getFullYear()
getMonth() Returns the current month, as a number from 0-11 var myDate new Date() var CurrentMonth myDate.getMonth()
getDate() Returns the current day of the month, from 1-31 var myDate new Date() var CurrentDate myDate.getDate()
getHours(), getMinutes(), getSeconds() Returns the current hour (0-23), minute (0-59), or second (0-59) var myDate new Date() var CurrentHour myDate.getHours()
23
Warning
  • Declaring a variable using new won't prevent the
    variable from automatically converting to any
    data type assigned to it!

24
Displaying the Current Date
  • lthtmlgtltheadgtlttitlegtMethodslt/titlegtlt/headgt
  • ltbodygt
  • ltscriptgt
  • var today new Date()
  • var weekFromToday new Date(today.getFullYear
    (),

  • today.getMonth(),
  • today.getDate()
    7)
  • alert("Today's date is " today "\n"
  • "A week from today is "
    weekFromToday)
  • lt/scriptgt
  • lt/bodygtlt/htmlgt

Date objects have tobe created using new
Tip you can get code help for Date in
Dreamweaver by entering Date( and
looking at the help popuped up above it.
If not shown try pressing ctrl-spacebar to
display it Notice it has 4 constructors
25
Displaying the Current Date in short format
Use today.getMonth today.getDate, and
today.getFullYear Example - replace
today in the previous slide's alert with
(today.getMonth() 1) "/" today.getDate()
"/" today.getFullYear() Add similar code
using weekFromTodayWhy is today.getMonth() 1
inside parentheses? Try removing them and see
what happens. Why am I adding 1 to
today.getMonth()?
26
Topics
  • Introduction to JavaScript
  • Positioning a script
  • Variables
  • Type conversions
  • Concatenation
  • HTML forms
  • Document Object Model
  • Functions
  • Form Validation
  • Debugging
  • Stuff...

27
Data Type Conversions
  • All HTML form input values are text strings
  • What if you need to change a value to a number?
  • Motivations
  • Determine if an input number value is within a
    specific range
  • Perform an addition operation on a form input

28
JavaScript Conversion Functions
  • Converting a string to a number
  • parseInt() converts a string to a number, and
    removes any fractional values
  • parseFloat() converts a string to a number, and
    includes any fractional values
  • Examples

document.frmForm1.txtResult.value
parseInt(value1) parseInt(value2) document.fr
mForm1.txtResult.value parseFloat(value1)
parseFloat(value2)
29
Code help for parseInt and parseFloat
  • In Dreamweaver Code view within script element
  • press Ctrl Spacebar at the same time
  • Type the letters you 'think' the command begins
    with (and/or scroll up and down to view options)

30
Converting Numbers to Strings
  • Concatenate number to an empty string
  • Example
  • myNumber is now a String

var myNumber 13 myNumber myNumber ""
31
Concatenating Number Values and String Values
  • is an overloaded operator in JavaScript
  • used for both addition and concatenation
  • What if you combine strings and numbers in the
    same operation?
  • add 2 numbers result is a number
  • add a string to a number result is a string
  • add a number to a string result is a string
  • If an operand on either side of the is a
    string, the result is a string

32
Given the following variable declarations, what
is displayed by each JavaScript alert? var
input1 "15" var input2 10.4 var input3
5 alert(input1 input2 input3)
______________________ alert(input3 input2
input1) ______________________ alert(input1
(input2 input3))______________________alert(in
put1 input3) ______________________
33
Topics
  • Introduction to JavaScript
  • Positioning a script
  • Variables
  • Type conversions
  • Concatenation
  • HTML forms
  • Document Object Model
  • Functions
  • Form Validation
  • Debugging
  • Stuff...

34
HTML Forms
  • Enhanced HTML documents that allow users to enter
    inputs onto Web pages using common interface
    controls
  • Text inputs, radio buttons, command buttons, etc.
  • When the user submits the Web page, the form
    passes the input values to the Web server
  • Input values are called parameters
  • Values are passed to the server in a parameter
    list

35
Creating a Form
  • form tag attributes
  • name identifies the form internally within the
    Web page
  • Example name"customer"
  • Form ID newer syntax for identifying a form.
    If used, the name attribute and id should be the
    same
  • Example id"customer" name"customer"
  • action specifies the action the Web server
    performs with the form parameter list
  • Usually involves calling a script or program that
    runs on the Web server (not in the users browser
    like JavaScript)
  • method how the Web server processes the
    parameters
  • GET passes the parameters as a list on the URL
  • POST sends the parameters directly to the
    receiving program

36
Confusion between id and name attributes
  • The id attribute (for example id"one") can be
    added to any HTML element.lttable id"data"gt
    including form and input tags
  • An element identified by a tag can be referenced
    in JavaScript using the document.getElementById
    methoddocument.getElementByID("data")
  • This can allow modifying just about any aspect of
    a page's appearance using JavaScript
  • In addition, if a style sheet is linked to the
    page, id's can apply id styles to an element
  • Form tags and form element tags (input, select
    and textarea) allow using the name attribute.
  • Names identify inputs to be sent to a Web server
    and can be used to access form input values using
    JavaScript. For example JavaScript accessing an
    input value might be document.formName.inputNam
    e.value And a server jsp program reading the
    inputName value would use request.getParameter("
    inputName")
  • The name attribute must be used for user form
    inputs with values that are to be sent to a web
    server
  • If omitted, the value the users selects or enters
    for the input will NOT be sent to the server.

37
Accessing form elements
  • Array Notationdocument.formsindex.elementsind
    ex.propertyOrMethodName
  • Must know the index number (order in which the
    form and element appear in the page)
  • Be warned that if you place any of the inputs in
    a different order or omit one and use array
    notation the array indexes will be off and the
    code will not work!
  • Which is why I use names instead of array
    indexes.
  • names (a good choice with javascript)document.fo
    rmName.elementName.propertyOrMethodNameordocumen
    t.formsindex.elementName.propertyOrMethodName
  • Names are easier to read and understand than
    array notation
  • Except when validating radio inputs (more later)
  • idsdocument.getElementByID("fname").value

38
Example Form Tag
  • ltform name"customer_order"
  • method"post" action"ProcessOrder.jsp"gt
  • form input elements and text go here
  • lt/formgt

39
Form Elements
  • Most form elements are defined using the input
    tag
  • ltinput type"input_type"
  • name"input_name"
  • value"input_value"gt
  • Type text, button, radio, etc.
  • Name used to reference the element internally
  • Value the elements initial or current value

40
HTML Form Elements
Description Function Type Sample Tag
Text field Entering a single line of text text ltinput type"text" name"name"gt
Password field Entering a single line of text with values masked as "" Password ltinput type"password" name"userpwd"gt
Command button Starting an action such as executing a script or program Button ltinput type"button" value"Whatever"gt
Submit command button Submitting a form to the Web server Submit ltinput type"submit" value"Login"gt
Reset command button Returning the form to its original state (clearing/resetting input values) Reset ltinput type"reset" value"Reset"gt
Radio button (or option button) Selecting a single value from a predefined group of item values Radio ltinput type"radio" name"pmtmethod"gt
Check box Specifying whether a value is true or false Checkbox ltinput type"checkbox" name"paid"gt
Lab1 introduces the HTML5 required attribute and
typeemail, number and date
41
More HTML Form Elements
Description Function Type Attribute Sample Tag
Text area Entering multiple lines of text, such as a paragraph Not used lttextarea name"comments"gt Initially displayed textlt/textareagt
Selection list Selecting a single item from a predefined list of items Not used ltselect name"colors"gt ltoption value"1"gtRedlt/optiongt lt/selectgt
Hidden element Storing a data item that is not visible to the user Hidden ltinput type"hidden" name"datemodified" value"stored data"gt
42
Text Fields
  • Single line of text data
  • Types
  • Text
  • Password
  • All HTML form data is entered as text
  • Characters, dates, numbers they are all text

43
Text Field Example
  • ltpgtPlease enter your name
  • ltinput name"UserName" type"text"gt
  • lt/pgt

44
Buttons
  • Types
  • Submit
  • Reset
  • Button
  • Difference between Submit and Button?
  • Submit automatically submits to the Web server
  • Button requires the programmer to write
    JavaScript code to make something happen

45
Button Examples
  • ltform name"username" action"nextPage.php"gt
  • Please enter your name ltinput type"text"
    name"name"gtltbrgt
  • ltinput type"submit" value"Submit Name"gtltbrgt
  • ltinput type"reset" value"Clear Form"gtltbrgt
  • ltinput type"button" value"Run Script"
    onclick"javaScriptFunction()"gt
  • lt/formgt

46
Radio Buttons
  • Each individual button is part of a radio button
    group
  • The name is the same for all buttons in the group
  • It references the value of the currently-selected
    button
  • The value and label attributes are different for
    each button

47
Radio Button Code Example
48
Check Boxes
  • Indicates a data value that can have one of two
    values
  • General syntax
  • The checked attribute makes the box checked at
    form startup
  • ltinput type"checkbox" name"boxName"
    value"boxValue" checkedgt

49
Check Box Example
  • ltpgtPaid in Full
  • ltinput name"paidStatus"
  • type"checkbox"
  • value"PAID"
  • checkedgt
  • lt/pgt

50
Selection Lists
  • Defines a list from which the user can select one
    of a series of values
  • Often used to display data retrieved from a
    database
  • List value is the value of the selected list item

51
Selection List Example
  • ltselect name"products"gt
  • ltoption value"shorts"gtShortslt/optiongt
  • ltoption value"tents"gtTentslt/optiongt
  • ltoption value"fleece"gtWomen's Fleecelt/optiongt
  • ltoption value"sandals"gtChildren's
    Sandalslt/optiongt
  • lt/selectgt

52
Text Area
  • Input field that can contain multiple lines of
    unformatted text
  • You can specify the length and width
  • Unlimited number of characters can be entered
  • Sort of - this is browser dependent
  • if you want to allow uploading entire books
    consider using the HTML input type"file"

53
Text Area Example
  • lttextarea name"instructions" cols"40"
    rows"10"gt Initial Textlt/textareagt
  • Closing tag is required ( /gt not allowed for the
    opening tag)

54
Hidden Form Elements
  • Useful for storing information that you dont
    want the user to see
  • Example passing values from one form to another
  • Syntax
  • ltinput type"hidden" name"userName"
  • value"MORRISCM"gt

55
ltform name"example" action"process.jsp"
method"post"gt ltinput type"text"
name"quantity"gt ltinput type"text"
name"productID"gt ltinput type"submit"
value"Submit Order"gtlt/formgt
  • When this form is submitted
  • A) parameters are passed as a list on the URL
  • B) parameters are passed directly to the web
    server
  • C) What parameters? There are no parameters

56
ltselect name"products"gt ltoption
value"shorts"gtShortslt/optiongt ltoption
value"tents"gtTentslt/optiongt ltoption
value"fleece"gtWomen's Fleecelt/optiongt ltoption
value"sandals"gtChildren's Sandalslt/optiongtlt/sele
ctgt
  • When this page is shown
  • A) This is displayed
  • B) This is displayed

57
  • When the above page is shown it is possible to
    select more than one at the same time. But
    when using radio buttons only "one" should be
    selectable at a time. Why can more than one be
    selected?
  • A) The value's should all have the same value
    (i.e., valueitems for example)
  • B) The name's should all be the same (i.e.,
    nameitems)
  • C) The input type should be typeoption for all
    of them
  • D) None of them have a closing lt/inputgt tag

58
Topics
  • Introduction to JavaScript
  • Positioning a script
  • Variables
  • Type conversions
  • Concatenation
  • HTML forms
  • Document Object Model
  • Functions
  • Form Validation
  • Debugging
  • Stuff...

59
Browser Object Model (BOM)
  • Hierarchy of objects providing programmatic
    access to the pages displayed in the browser
  • Not standardized among different browsers
  • In practice most browsers have common
    implementations of browser objects
  • Document Object Model (DOM)
  • Subset of the browser object model
  • This IS standardized and compatible (mostly)
    across different browsers
  • Many developers, books, articles, etc. refer to
    the DOM and don't refer to the BOM.

60
Browser Object Hierarchy (basics)
window
document
history
location
navigator
screen
forms array
images array
links array
frames array
elements array
Document Object Model (DOM)
61
HTML Document Object Hierarchy
window
document
form
text
submit
textarea
reset
password
checkbox
select
radio
button
option
62
Navigating the HTML Document Model
  • Hierarchy to a form object is called its object
    path
  • Reference a form object using dot syntax

window.document.form_name.object_name
Enter the desired form name and object name (if
a form is named, it is usually referenced by
name rather than using forms0 same for
elements contained within a form)
Current window (always)
Current HTML document (always)
window.document.forms0.elements0
63
Example
Form name student
You would reference the current value of DOB
as window.document.student.DOB.value NOTE
You can omit window when referencing a form
object For example document.student.DOB.value Som
e browsers also allow omitting document
Text field name DOB
64
Topics
  • Introduction to JavaScript
  • Positioning a script
  • Variables
  • Type conversions
  • Concatenation
  • HTML forms
  • Document Object Model
  • Functions
  • Form Validation
  • Debugging
  • Cookies

65
Creating a Custom Function
  • Create the function declaration within script
    tags
  • Defines the function
  • Function name
  • Parameter list (optional)
  • Commands that function executes
  • Value that the function returns (optional)
  • Create the function call(s) in the Web page body
  • Calls the function
  • Passes parameter values to it (if function has
    them)

66
Creating a Custom Function
Function definition
Function calls in body
67
Function Declaration Syntax
function function_name (parameter1, parameter2,
) function_commands return
return_value
Optional only a parameter name is used no
type information
68
Function Call Syntax
function_name (parameter1, parameter2)
function validateAge(age) if(age "")
alert("Please enter your age") return
false else if(isNaN(age) true)
alert("Please enter a number for your
age") return false return
true function validateUserEntries()
if(validateAge(document.employee.age.value)
false) return false // additional code
checking other entries
Whatever the user has entered in the text input
is sent to validateAge as a parameter
69
Event Handlers
  • Event handler function that executes as a
    result of a user action
  • You can use a JavaScript function as an event
    handler for a form button
  • Names of commonly-used event handlers
  • onsubmit (for form submit buttons)
  • onclick (for regular command buttons, radio
    buttons, check boxes, hyperlinks)
  • onselect (for text fields and text areas)
  • onchange (for text fields, text areas, selection
    lists)
  • onmouseover (for many html elements)
  • Place the event handler name and its associated
    action directly within the form item tag as an
    attributevalue
  • The action is usually a JavaScript function call

ltinput typebutton event_handler_name"JavaScriptF
unctionCall()"gt
70
Anonymous Functions
  • Some of the stranger looking code in JavaScript
    revolves around anonymous functions
  • If used as below not very strange and pretty much
    interchangeable with non-anonymous functions

71
Anonymous Functions
  • This anonymous (sort of it is assigned to
    sayHello) function works
  • This doesn't work
  • Yet this non-anonymous function works

anonymous and non-anonymous functions aren't
quite the same
72
Number of other anonymous issues
  • But I'm not going to cover them here
  • We'll return to this when discussing jQuery

73
Examples of Event Handlers
ltinput type"text" name"inputName"
value"Joline" onchange"SelectNameText()
"gt
ltinput type"button" name"showGreeting"
value"Show Greeting" onclick"ShowGreetin
gText()"gt
ltimg namecarImage srccar.jpg
onmouseover"switchImage()"gt
74
Finding Errors (continued)
  • Sources of errors
  • Error in the command calling the function
  • Misspelled the function name?
  • Wrong capitalization?
  • Forgot the parentheses () after the function
    name?
  • Error in the function code itself
  • Mismatched curly braces ?
  • Missing double or single quotes?
  • Wrong spelling or capitalization of commands?
  • ??

75
What will happen when the button is clicked?
  • Assume browser is set to display errors
  • A) There must be an error somewhere or you
    wouldn't be asking this so an error is
    displayed
  • B) Hello is displayed
  • C) No error, yet Hello isn't displayed
  • D) No idea what happens

76
Answer to previous question
  • C onclick"displayMessage" should be this
    onclick"displayMessage()"
  • Omitting the parentheses after displayMessage
    doesn't make the browser show an error yet
    displayMessage won't be called!

77
What will happen when the button is clicked?
  • Assume browser is set to display errors
  • A) An error is displayed
  • B) Hello is displayed
  • C) No error, yet Hello isn't displayed
  • D) No idea what happens

78
Answer to previous question
  • A function displayMessage should be
    function displayMessage()
  • Omitting the parentheses after displayMessage in
    the function declaration does cause a JavaScript
    error

79
What will happen when the button is clicked?
  • Assume browser is set to display errors
  • A) An error is displayed
  • B) Hello is displayed
  • C) No error, yet Hello isn't displayed
  • D) No idea what happens

80
Answer to previous question
  • A onclick"displaymessage()" should be
    onclick"displayMessage()"

81
Topics
  • Introduction to JavaScript
  • Positioning a script
  • Variables
  • Type conversions
  • Concatenation
  • HTML forms
  • Document Object Model
  • Functions
  • Form Validation
  • Debugging
  • Stuff...

82
Topic
  • Validating HTML form inputs
  • determining
  • If users entered something for required values
  • If users entered correct values
  • Why do this using client-side scripts?
  • Saves time/traffic of sending incorrect/incomplete
    inputs to the Web server
  • Saves the Web server the processing time needed
    to validate the inputs? Perhaps not you should
    also validate on the server because users can
    find ways to submit stuff to the server bypassing
    JavaScript validation (can you think of one
    really easy way to do this?)

83
Form Validation Function
  • Function that is called before a form is
    submitted to the Web server for processing
  • Contains a series of if or if/else tests to
    determine if form inputs are correct
  • If all inputs are correct, function returns a
    value of true, and submits the form to the Web
    server
  • If an input is not correct
  • function displays an alert to inform the user
    about the problem
  • sets the focus (or selects highlights contents)
    to the input needing attention
  • returns a value of false, and does not submit the
    form to the Web server

84
Form Validation Function using if Structures
function validation_function_name if
(error_condition_1) alert ("error_condition_1_d
escription") set_focus_to_input_with_error ret
urn false if (error_condition_2) alert
("error_condition_2_description")
set_focus_to_input_with_error return false
if (error_condition_3) alert
("error_condition_3_description") set_focus_to_i
nput_with_error return false return
true
85
Form Validation Function using if/else if
Structures
function validation_function_name var ret
false if (error_condition_1) alert
("error_condition_1_description") set_focus_to_i
nput_with_error else if (error_condition_2)
alert ("error_condition_2_description")
set_focus_to_input_with_error else if
(error_condition_3) alert ("error_condition_3_d
escription") set_focus_to_input_with_error
else ret true return ret
Is this better than using the previous slide's
approach?
86
  • Strategy for validating values
  • Steps
  • First check to see if required field value is
    entered
  • Next check to see if value is of the correct data
    type (if needed)
  • Finally check for value falling within a specific
    range (if needed)
  • Repeat these steps for all other user inputs on
    the page
  • Work from the top to bottom, left to right as
    people normally read a page when doing this
    validation and do all validations for each
    element as you work from the top to the bottom.
  • When an error is found, notify the user of the
    error and dont do further validation until the
    user corrects this error and resubmits the form.

87
Calling a Form Validation Function
  • Create an onsubmit event handler for the form
  • Syntax
  • Result
  • If the function returns the value true, the
    submit input submits the form to the Web server
  • If the function returns the value false, the
    submit input does not submit the form
  • Caution
  • If you omit the return before the function name
    the form will always be submitted even when
    false is returned by the function

ltform name"frmExample" action"nextPage.htm"
onsubmit"return Validation_Function_Name()"gt
88
Calling a Form Validation Function (alternate)
  • Create an onclick event handler for the submit
    button
  • Syntax
  • Works almost the same as calling from a form's
    onsubmit
  • Except IE allows a form to be submitted by
    pressing the Enter key when an ltinput gt tag is
    currently selected. If this is done, it bypasses
    the submit button and the validation function
    isn't called.
  • Firefox and other browsers don't bypass
    validation if a submit input's onclick is used.
  • Use the previous slide's form onsubmit approach
    and do not use a submit button's onclick event.

ltinput type"submit" value"Submit"
onclick"return Validation_Function_Name()"gt
89
Validating using onblur
  • onblur event that occurs when the focus shifts
    away from the currently selected element
  • Allows validating an entry the moment the user
    tabs or clicks to the next form element
  • Must additionally revalidate all elements when
    the form is submitted
  • The user might not tab or click to a required
    form element and thereby not generate an onblur
    event
  • Pressing the enter key while an ltinput gt is
    selected submits the form if using IE (and
    doesn't generate an onblur event)

90
Validation best practice
  • Use onsubmit"return validationFunction()" in
    your form tag to check entries
  • Consider using onblur to immediately check
    entries
  • Doing both means more coding effort ?
  • if time is limited, use onsubmit and omit the
    onblurs
  • Repeat the validation in the server side program
  • Because users might find way to submit data that
    bypasses your JavaScript validation

91
What will happen if the user clicks the submit
button without entering anything?
  • A) Nothing
  • B) An alert is displayed saying Please enter a
    number
  • C) An alert is displayed saying Please enter a
    number and nextPage.htm is displayed
  • D) No alert and nextPage.htm is displayed
  • E) No idea

92
What will happen if the user clicks the submit
button without entering anything?
  • A) Nothing
  • B) An alert is displayed saying Please enter a
    number
  • C) An alert is displayed saying Please enter a
    number and nextPage.htm is displayed
  • D) No alert, but nextPage.htm is displayed
  • E) No idea

93
Validating Numeric Inputs
  • Use the isNaN() function
  • Returns true if the value is not a number
  • An empty string "" will evaluate as false
    indicating it is a number (when clearly an empty
    string is not a number!)
  • So prior to the isNaN() test, add another test to
    ensure something is entered.
  • Returns false if the value is a number (or is an
    empty string)
  • Syntax

if (isNaN(document.example.num.value) true)
alert ("You must enter a value that is a
number") document.example.num.select() return
false
94
Validating Numeric and Text Inputs
  • Regular Expressions
  • Syntax

var testNumber /\d/ if(testNumber.test(d
ocument.frmCourse.c_credits.value) false)
alert("Please enter a number for course
credits") document.frmCourse.c_credits.select()
return false
testName /a-zA-Z/ if(testName.test(exampl
e.name.value) false) alert("Please enter
only letters for your user name") example.name.s
elect() return false
http//gnosis.cx/publish/programming/regular_expre
ssions.html
95
What will happen if the user clicks the submit
button after entering a number?
  • A) Nothing
  • B) An alert is displayed saying Please enter a
    number
  • C) An alert is displayed saying Please enter a
    number and nextPage.htm is displayed
  • D) No alert and nextPage.htm is displayed
  • E) No idea

96
Validating Date Inputs
  • There are many ways to do this none
    particularly elegant
  • Use user entry to create a new Date object and
    test for NaN
  • Doesn't work in all browsers and doesn't do a
    very good job of validating the date
  • Write your own custom function to validate the
    date
  • gets lengthy
  • Use a regular expression to validate the date
  • Also lengthy (and cryptic) if you attempt
    rigorous validation
  • Examples these aren't completehttp//cs.uwec.e
    du/morriscm/priv/Spr14/CS268/_ClassNotes/customDa
    teValidationFunction.htm

97
Validating Numeric Ranges
  • Assuming you have already confirmed the user
    input is a valid number using isNaN, the syntax
    is

var PIN parseInt(document.login.UserPIN.value)
if (PIN lt 1000 PIN gt 9999) alert("The PIN
must be a number between 1000 and 9999")
document.login.UserPIN.select() return
false
98
Validating Numeric Ranges
  • Assuming you have already confirmed the user
    input is a valid number using isNaN and all you
    care about is that it be a 4 digit number

if (document.frmExample.num.value.length ! 4)
alert("The number must have 4 digits")
document.frmExample.num.select() return
false
99
Validating Numeric Entry and Length
  • Using Regular Expression
  • Example requires 4 digit number it can begin
    with zeros
  • Example requires 4 digit number beginning with
    1 or higher

rePin /0-94/ if(!rePin.test(document.frmNa
me.txtNumber.value))
rePin /1-90-93/ if(!rePin.test(document.
frmName.txtNumber.value))
http//www.zytrax.com/tech/web/regex.htm
100
Order of validation example
  • Top to bottom, left to right (as if reading)
  • The following has top to bottom order
  • Do all validations for name first, then age, then
    date

101
Assume we only care that "something" is entered
for name. Only one validation is needed for name.
We need three separate tests to validate age.
isNaN won't catch empty entries. And we need
to ensure age is in a (somewhat) reasonable range.
This regular expression will catch empty entries
(no need for a separate test). It doesn't ensure
a reasonable range but I'm not going to require
this for this class.
Notice that if an error is discovered, the user
is notified without trying to find additional
errors. This is avoid overwhelming the user with
multiple errors all at once. After fixing the
error and resubmitting, additional errors will be
brought to their attention.
102
Validating a select list
  • If size"1" (the default value) the first item in
    the list is always selected by default (until the
    user selects something else)
  • The selectedIndex of the first item in the list
    is 0 (zero)
  • If size is greater than 1 (a list instead of a
    drop down combo box) by default, nothing is
    initially selected
  • and the initial value for selectedIndex is -1
  • selectedIndex is what you check to see if
    something is selected. If it is -1 the user
    needs to select something.

103
select example
size gt 1 so selectedIndex's initial value is
-1 (if size 0 selectedIndex'sinitial value
is 0 and the firstitem is selected by default)
104
Validating checkboxes
  • First of all, why validate a checkbox?
  • Perhaps you've got a single checkbox at the
    bottom of the page for the user to check
    indicating they have read and accept an
    agreement? (see this all the time)
  • In other instances, there may be no need to
    validate a checkbox
  • Perhaps there is a list of checkboxes indicating
    user preferences and there is no need for a
    user to check any of them
  • Don't validate unless it makes sense to do so!

105
Validating checkboxes
checked property is true if checked
106
Validating radio inputs
  • A group of radio inputs will all have the same
    name
  • You must check each array element to see if one
    of them is checked
  • If there are lots of radio inputs in the group
    or if the group of radio inputs is generated from
    a database query and you don't know how many will
    be generated
  • Use a loop to process the array storing the radio
    inputs and see if one is selected

107
Validating radio inputs(without using a loop)
Look at each array element individually to see if
checked.In this example there are only two
elements in the group.
108
Validating radio inputs(using a loop assume
there are "lots" of choices in the radio group
color)
The length property stores how many elements are
in the array
If any element in the array is checked there is
no need to continue looking there can only be
one selected (checked) element in a radio
group. If index is still -1, a checked radio
input wasn't found in the array
109
Dreamweavers form validation
  • Dreamweaver will automatically generate a
    Javascript function to validate form inputs

110
Dreamweaver allows you to
  • Specify required fields
  • Specify that field data types must be numbers
  • Specify number ranges

111
Dreamweaver Pros and Cons
  • Pros?
  • Easier and faster to add a script!
  • Cons?
  • You lose control of
  • Message text
  • Selecting the input with the error
  • Can't validate dates
  • Single alert displays message about each error
    (is this good?)
  • Nasty looking JavaScript care to modify the
    generated code?

112
Dreamweaver Generated JavaScript
Easy to understand and modify this code no?
113
Similar code rewritten for human eyes
Easy to understand and modify this code
(including features Dreamweaver can't add yes!)
114
Topics
  • Introduction to JavaScript
  • Positioning a script
  • Variables
  • Type conversions
  • Concatenation
  • HTML forms
  • Document Object Model
  • Functions
  • Form Validation
  • Debugging
  • Stuff...

115
Debugging JavaScript Programs
  • What happens when a script fails?
  • Whatever it was supposed to do doesn't happen
  • No error messages unless the browser you are
    using is configured to show the error(s)
  • All of the major browsers now have decent
    JavaScript debugging tools built in.
  • I'll show a few in class

116
All browsers cache cookies and pages
  • For example Firefox enter aboutcache in the
    address bar

Make sure you aren't viewing a cached page that
doesn't have your changes in it! When using
Firefox, press Ctrl-F5 at the same time to make
Firefox get a new page instead of using its cache.
117
Finding Errors when the error console isn't
enough
  • Strategies
  • Determine if the function is actually getting
    called
  • Display a short alert message as the first line
    of the function
  • If the function is getting called, then determine
    which line is crashing
  • Display a short alert before every line to see
    how far you are getting
  • or
  • Cut out approximately half of the code and see if
    the error still occurs. If it does, the error is
    in the remaining half, if not, the error is in
    the half you cut out.
  • When cutting out code save it somewhere so you
    can add it back after you find the error.
  • Be careful where you cut the code. You can
    introduce new errors if you cut in a way that
    introduces mismatched curly braces or splits a
    string constant across two lines.

118
Topics
  • Introduction to JavaScript
  • Positioning a script
  • Variables
  • Type conversions
  • Concatenation
  • HTML forms
  • Document Object Model
  • Functions
  • Form Validation
  • Debugging
  • Stuff...

119
Displaying a Confirm Message
  • Confirm message is similar to an alert but it
    has an OK and a Cancel button

120
Examples using confirm
Alternate and equivalent code
121
The following code segments are equivalent
  1. Yes
  2. No
  3. Don't know

122
Changing the window location
  • Doesnt open a new window, changes location of
    current browser window
  • window.location.href "new URL"
  • Examples window.location.href
    "http//www.google.com" window.location.href
    "orders.htm" window.location.href
    "..\products\catalog.htm"

123
window.open
  • Pop up ad blockers will block a window.open
    command from events other than the onclick event
  • window.open called from an onclick event is
    allowed by most pop up blockers.

Blocked
ltbody onload"window.open('advertisement.html')"gt
ltimg src"drgdx.gif" onmouseover"window.open('ad
vertisement.html')"gt
Not blocked
ltinput type"button" value"Open Window"
onclick"window.open('advertisement.html')"gt ltimg
src"drgdx.gif" onclick"window.open('advertiseme
nt.html')"gt
124
Opening a new window
  • var window_id window.open(url, name, options,
    replace )
  • var window_id is optional if used, window_id
    can be used to close, resize, or move the new
    window to a different spot on the screen.
  • url is optional if omitted a blank browser
    window is displayed
  • name is optional
  • What happens if you execute the window.open()
    method twice, with the same name (also called
    target) argument? Like HTML-generated windows, if
    you specify the name of a window that already
    exists, open() simply uses that existing window
    rather than opening a new one.
  • options define the properties of the new
    browser window
  • replace is optional - If true, the new location
    will replace the current page in the browser's
    navigation history. Note that some browsers will
    simply ignore this parameter

125
Opening a new window
  • Option list parameters

toolbar displays the browser toolbar toolbaryes toolbarno
location displays the address field in the browser locationyes locationno
directories displays the window title bar links to frequently used URLs directoriesyes directoriesno
status displays the status bar at the bottom edge of the window statusyes statusno
menubar displays the browser menu bar menubaryes menubarno
scrollbar displays scrollbars on the browser scrollbaryes scrollbarno
resizable allows the user to resize the browser window resizeableyes resizeableno
width, height specifies the browser window width and height, in pixels width300 height200
126
Opening a new window
  • Example

var wParams "height160,width550,menubarno,too
lbarno,titlebarno,"
"resizableno,locationno,statusno,directoriesno
" var adWindow window.open("ad.htm","",wParams
) adWindow.moveTo(230, 350)
127
Arrays
  • Code creating an array and retrieving its
    contents

ltscriptgt var classes new Array() classes0
"CS 491" classes1 "CS 352" classes2
"CS 319" classes3 "CS 163" function
displayClasses() for (var i 0 i lt
classes.length i) document.write(classesi
"ltbrgt") lt/scriptgt
128
Arrays
  • HTML input elements are stored as arrays
  • Example

function DisplayElements() var msg
"" for(var i 0 i lt document.frmOrderItem.elem
ents.length i) msg
document.frmOrderItem.elementsi.name ""
document.frmOrderItem.elementsi
.value "\n" alert(msg)
129
Arrays
  • Radio inputs are in arrays
  • Validating a radio input is checked sometimes
    requires array processing

function ValidateRadioSelected() var index
-1 for(var i0 iltdocument.frmOrderItem.color.le
ngth i) if(document.frmOrderItem.colori.c
hecked) index i break if(index
gt 0) alert(document.frmOrderItem.colorindex
.value " is checked") return true
else alert("Please select a
color") document.frmOrderItem.color0.focus()
return false
130
window.setTimeout
  • Can omit the window.
  • Executes Javascript commands after a specified
    amount of time elapsessetTimeout("commandOrFunct
    ion", timeToWaitInMilliSeconds)setTimeout("aler
    t('5 seconds have elapsed')", 5000)

131
window.setInterval
  • Similar to setTimeout except will continue to
    execute the command(s) again and again after the
    specified time elapses.setInterval(commandOrFunc
    tion, timeToWaitInMilliSeconds)setInverval(aler
    t("5 seconds have elapsed"), 5000)

http//ejohn.org/blog/how-javascript-timers-work/
132
window.screen
  • Useful to center browser window in the screen
  • But only if you opened the window using
    window.open
  • Can be used to download smaller images to
    browsers with lower color depths or resolution
  • Which could make page downloads faster
  • But this is a lot of work and normally isn't done
  • screen.height screen's height in pixels
  • screen.width screen's width in pixels
  • screen.colorDepth bits used to display color

133
What will this do?
Here's the code as text if you want to copy and
paste it in a new page and then test it to see
what it does
lthtmlgtltheadgtlttitlegtWhat does this
do?lt/titlegt ltscriptgt var x 0 var y 0 var
direction "down" var winID function
initializeBrowser() var wParams
"height200,width400,top0,left0" winID
window.open("", "", wParams) setInterval('moveB
rowser()', 1) function moveBrowser()
if(direction "down" y gt
screen.availHeight - 200) direction
"up" else if(direction "up" y lt 50)
winID.close() this.close() if(dire
ction "down") x 4 y 4 else
x - 4 y - 4 winID.moveTo(x,
y) winID.focus() lt/scriptgt lt/headgt ltbodygt lt
input type"button" onclick"initializeBrowser()"
value"Start"gt lt/bodygtlt/htmlgt
134
JavaScript Events
  • Ways to assign
  • inline (works in all browsers) ltinput
    type"button" onclick"myFunction()"gt
  • traditional (using JavaScript works in all
    browsers) obj document.getElementByID("relevan
    tID") obj.onclick myFunction
  • W3C (JavaScript can add several event listeners
    to the same event for the same object) obj
    document.getElementByID("relevantID") obj.addEve
    ntListener('click', myFunction, false)
  • Microsoft (JavaScript) obj document.getElement
    ByID("relevantID") obj.attachEvent('click',
    myFunction, false)

http//www.quirksmode.org/js/introevents.html
135
JavaScript Events
  • If you use the traditional method (works in all
    browsers)
  • declare function with a single parameter (any
    name will do but e is often used)function
    myFunction(e)
  • Parameter references the event object in browsers
    OTHER than IE
  • If using IE parameter is ignored
  • IE references the event object using window.event
  • Detecting browser (and type of code to
    use)if(window.event) // IE orif(e) // not
    IE assumes named parameter e

136
JavaScript Events
  • Event object properties/methods
  • Varies between IE and rest of world
  • The following link lists many of them

http//www.javascriptkit.com/domref/domevent.shtml

137
JavaScript Events
  • Recommendation?
  • Use traditional rather than inline if you need
    access to the event object
  • Useful to prevent Firefox from automatically
    doing drag and drops with images
  • Some say use it all the time
  • Separates code from html markup
  • Allows access to the event object
  • (IE always allows access - other browsers need an
    e parameter)
  • But results in more complicated codesee next
    slide

138
JavaScript Events
Less code and less complicated
139
JavaScript Events
Wait until page finishes loading to initialize
the events
Retrieve the element and assign a function to
relevant events
I'm not showing it, but you will need to
pre-cache the images
Retrieve the element triggering the event. Code
varies between IE and rest of world
Recent Firefox versions automatically drag all
images when mouse is pressed and dragged over the
image. IE throws an error over this code. Other
browsers just ignore it. This prevents Firefox
from dragging the image. See next slide for
revised way to do this.
140
Block image dragging
141
What is the result?
  1. Name was Smith
  2. Name was not Smith
  3. Same as previous question, you didn't change a
    thing

142
Pitfall Using or
  • ' ' is the assignment operator
  • Used to assign values to variables
  • Example var name "Smith"
  • ' ' is the equality operator
  • Used to compare values
  • Example if ( name "smith")
  • Javascript will accept this error
    if( name "smi
Write a Comment
User Comments (0)
About PowerShow.com