1 cs 21a beginning javascript programming project 2 creating pop-up windows, adding scrolling...

111
1 CS 21A Beginning JavaScript Programming Project 2 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms Sonny Huang

Upload: jordan-nicholson

Post on 25-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

1

CS 21A • Beginning JavaScript

Programming

Project 2 Creating Pop-up Windows, Adding Scrolling Messages, and Validating

Forms Sonny Huang

2

Project 2 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms

Outline Explain the four basic components of a scrolling message Write a user-defined function to display a scrolling message in a

form text box Describe the If statement Define conditionals and discuss the conditional operands Define recursion Describe the focus() method Write a user-defined function to calculate mortgage payments Validate data entry using a nested If…Else statement Describe the parseInt(), parseFloat(), and isNaN() built-in

functions

3

Project 2 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms

Describe the math pow() method Write a user-defined function to format output in currency

format Discuss For and While loops Use the open() method to display another Web page in a pop-up

window Use the lastModified property to display the date a Web page

was last modified

4

Introduction

Introduction

We will create a Web page that will allow Home Finders Nationwide Realty customers to calculate the amount of their monthly mortgage payment, based on the amount of mortgage, interest rate, and the number of years.

We will learn 1. how to add a scrolling message, which will introduce them to the substring() method and the If statement. 2.how to use JavaScript to validate forms.

5

Introduction

3.If…Else statements, the parseInt(), parseFloat(), and isNaN() built-in functions, as well as using the pow() method.4. writing functions to calculate and display the resulting monthly payment amount using the currency format.5. how to add a pop-up window to display information on using the mortgage payment calculator.

6

Introduction

We all experienced using the Internet to purchase or searching something.

Look for this web site homeadvisor.msn.com and other online lenders and realtors .

Do you search for a house online?

How do you feel about applying for loans online?

What are the important issues?

7

Project Two — Home Finders Nationwide Realty

We want to design a web page first loads a pop up windows to displays a message informing users of the new mortgage payment calculator.

8

Project Two — Home Finders Nationwide Realty

The web page also includes a scrolling message that constantly displays to remind visitors of the current low mortgage rate.

9

Project Two — Home Finders Nationwide Realty

The mortgage payment form allows users to calculate their monthly payment based on the amount of mortgage, interest rate, and years.

10

Project Two — Home Finders Nationwide Realty

We will use functions to validate data, calculate monthly payment, and display the result in currency format.

For the sense of up to date, we will have the last modification date displayed at the bottom of the page.

11

Project Two — Home Finders Nationwide Realty

Data Validation Requirement:If the information inputted is not a number or not a valid form than we should use the alert message box to notify the user and position the insertion point in the appropriate text box.

When all the entries are valid, the calculation function will be called to provide the monthly payment information.

12

Project Two — Home Finders Nationwide Realty

Calculations:

The formula for calculating a monthly payment is

Monthly payment =

loan * rate

(1-(1/(1+rate)payments))

13

Project Two — Home Finders Nationwide Realty

Starting Notepad and opening the home.htm file

14

Inserting a scrolling message on a Web page

Microsoft create marquee html tag.

<MARQUEE ...> creates a scrolling display and is an MSIE extension and will probably never be supported by any other browser.

The basic use of <MARQUEE ...> is simple. Put most any kind of markup between <MARQUEE ...> and </MARQUEE>.

<MARQUEE> Hi There! <IMG SRC="graphics/idocs.gif" HEIGHT=33 WIDTH=82

ALT="Idocs Guide to HTML"> </MARQUEE>

15

Inserting a scrolling message on a Web page

By using a JavaScript user defined function can create the scrolling effect as marquee and can compatible with all the browsers.

A scrolling message has four basic components:1. The display object defines where the scrolling object displays(status bar, or form text box).

2. The message is a text string assigned to a variable.

3. The position is the starting location in which the message first displays in the display object.

4. The delay is the length of time between when a message ends and when it starts to appear again.

16

Inserting a scrolling message on a Web page

Using the form’s text box to create the scrolling effect.

<FORM Name="msgForm"> <INPUT Type="text" Name="scrollingMsg"

Size="23"> </FORM>

Form:An HTML form is a section of a document containing normal content, markup, special elements called controls (checkboxes, radio buttons, menus, etc.), and labels on those controls. Users generally "complete" a form by modifying its controls (entering text, selecting menu items, etc.), before submitting the form to an agent for processing (e.g., to a Web server, to a mail server, etc.)

17

Inserting a scrolling message on a Web page

Input(one of the form’s control types):We could create two types of controls that allow users to input text. The INPUT element creates a single-line input control and the TEXTAREA element creates a multi-line input control.

Input tag’ Attribute definitionstype = text This attribute specifies the type of control to create. The default value for this attribute is "text".

name = name This attribute assigns the control name.

18

Inserting a scrolling message on a Web page

size = numberThis attribute tells the user agent the initial width of the control. The width is given in pixels except when type attribute has the value "text" or "password". In that case, its value refers to the (integer) number of characters.

19

Inserting a scrolling message on a Web page

Creating a form text box to display a scrolling message: Inserting the code in the section

20

Inserting a scrolling message on a Web page

21

Inserting a scrolling message on a Web page

Creating a user-defined function for a scrolling message We will create function scrollingMsg() to perform 1. Assign message.2. Check the end of the message.3. It assigns the next character in the message to the textbox.

The function requires three variables:var scrollMsg = "Mortgage rates are at their LOWEST!"

var msgSpace = "--- ---" var beginPos = 0

22

Inserting a scrolling message on a Web page

Put <SCRIPT LANGUAGE="JAVASCRIPT"><!--Hide from old browsers

var scrollMsg = "Mortgage rates are at their LOWEST!" var msgSpace = "--- ---" var beginPos = 0 after the Title tab.

23

Inserting a scrolling message on a Web page

24

Inserting a scrolling message on a Web page

Put the the user define function, scrollingMsg(), after the variable declaration.

function scrollingMsg() {

document.msgForm.scrollingMsg.value = scrollMsg.substring(beginPos,scrollMsg.length)+msgSpace+scrollMsg.substring(0,beginPos)

25

Inserting a scrolling message on a Web page

The scrollMsg and msgSpace are concatenated and assigned to the scrollingMsg text box through the following statement

document.msgForm.scrollingMsg.value = scrollMsg.substring(beginPos,scrollMsg.length)+msgSpace+scrollMsg.substring(0,beginPos)

Mortgage rates are at their LOWEST! --- ---

26

Inserting a scrolling message on a Web page

The form, msgForm, becomes property of document object. The text box, scrollingMsg, become property of document.msgForm object. The property value is the property of document.msgForm.scrollingMsg.

27

Inserting a scrolling message on a Web page

Increment the Position Locator Variable

beginPos = beginPos + 1

28

Inserting a scrolling message on a Web page

Entering an If Statement

29

Inserting a scrolling message on a Web page

if (condition) {          statements1 } else {          statements2

}

The condition can be any JavaScript expression that evaluates to true or false. The statements to be executed can be any JavaScript statements, including further nested if statements. If you want to use more than one statement after an if or else statement, you must enclose the statements in curly braces, {}.

30

Inserting a scrolling message on a Web page

31

Inserting a scrolling message on a Web page

32

Inserting a scrolling message on a Web page

Example. In the following example, the function checkData returns true if the number of characters in a Text object is three; otherwise, it displays an alert and returns false.

function checkData () {          if (document.form1.threeChar.value.length == 3) {                    return true          } else {                    alert("Enter exactly three characters. “

+  document.form1.threeChar.value + " is not valid.")

           return false           }}

33

Inserting a scrolling message on a Web page

If the beginning position is greater than the message length then set the beginning position to zero.

beginPos = beginPos + 1 if (beginPos > scrollMsg.length) { beginPos = 0 }

34

Inserting a scrolling message on a Web page

If the beginning position is greater than the message length then set the beginning position to zero.

beginPos = beginPos + 1 if (beginPos > scrollMsg.length) { beginPos = 0 }

35Using the setTimeout() Method to create a Recursive Function

Call

Recursion

A programming method in which a routine calls itself. Recursion is an extremely powerful concept, but it can strain a computer's memory resources

Using the setTimeout function to call itself to create Scrolling Effect.

window.setTimeout("scrollingMsg()",200)

36Using the setTimeout() Method to create a Recursive Function

Call

37Using the setTimeout() Method to create a Recursive Function

Call

Adding an Event HandlerWe will place an onload() even handler in the <Body> tag to create the scrolling message when the web page is load.

38Using the setTimeout() Method to create a Recursive Function

Call

39Using the setTimeout() Method to create a Recursive Function

Call

Insert the following statement<BODY onload="scrollingMsg()">

40

Saving the HTML file and Testing the page

41

The Mortgage Payment Calculator Form

To Assign a value to a text box object within a form, we need to use the form name, the text box name and the value attribute.

42

The Mortgage Payment Calculator Form

Inserting an Event Handler in an Anchor Tag

A link is a connection from one Web resource to another. Although a simple concept, the link has been one of the primary forces driving the success of the Web.

A link has two ends -- called anchors -- and a direction. The link starts at the "source" anchor and points to the "destination" anchor, which may be any Web resource (e.g., an image, a video clip, a sound bite, a program, an HTML document, an element within an HTML document, etc.).

43

The Mortgage Payment Calculator Form

An anchor name is the value of either the name or id attribute when used in the context of anchors. Anchor names must observe the following rules:

Uniqueness: Anchor names must be unique within a document. Anchor names that differ only in case may not appear in the same document.

String matching: Comparisons between fragment identifiers and anchor names must be done by exact (case-sensitive) match.

44

The Mortgage Payment Calculator Form

Thus, the following example is correct with respect to string matching and must be considered a match by user agents:

<P><A href="#xxx">...</A> ...more document... <P>

<A name="xxx">...</A>

45

The Mortgage Payment Calculator Form

We will use the onclick event handler within the <A> tag to triger a user defined function, doMort(). The doMort() function will clear the text box and place the insertion point in the Amount Mortgage box.

In an Html file the following statement should match with each other.<A HREF="#LoanCalc" onclick="doMort()">Estimate Mortgage Payment</A>

<A NAME="LoanCalc"></P>

46

The Mortgage Payment Calculator Form

47

The Mortgage Payment Calculator Form

48

Writing the doMort() User-Defined Function

We will use the onclick event handler within the <A> tag to triger a user defined function, doMort(). The doMort() function will clear the text box and place the insertion point in the Amount Mortgage box.

In an Html file the following statement should match with each other.<A HREF="#LoanCalc" onclick="doMort()">Estimate Mortgage Payment</A>

<A NAME="LoanCalc"></P>

49

Writing the doMort() User-Defined Function

focus Method. Gives focus to the specified object.

Syntax 1. fileUploadName.focus()2. passwordName.focus()3. selectName.focus()4. textName.focus()5. textareaName.focus()6. frameReference.focus()7. windowReference.focus()

50

Writing the doMort() User-Defined Function

Parameters fileUploadName is either the value of the NAME attribute of a FileUpload object or an element in the elements array.

passwordName is either the value of the NAME attribute of a Password object or an element in the elements array.

selectName is either the value of the NAME attribute of a Select object or an element in the elements array.

51

Writing the doMort() User-Defined Function

textName is either the value of the NAME attribute of a Text object or an element in the elements array.

textareaName is either the value of the NAME attribute of a Textarea object or an element in the elements array.

frameReference is a valid way of referring to a frame.

52

Writing the doMort() User-Defined Function

function doMort() { document.MortCalc.Amount.value=" " document.MortCalc.Rate.value=" " document.MortCalc.Years.value=" " document.MortCalc.Payment.value=" " document.MortCalc.Amount.focus() }

53

Writing the doMort() User-Defined Function

54

Writing the doMort() User-Defined Function

55

Validating the Mortgage Payment Calculator Form

56

Validating the Mortgage Payment Calculator Form

Validating Data Using the If… Else Statement

57

Validating the Mortgage Payment Calculator Form

58

Validating the Mortgage Payment Calculator Form

Using the indentation and braces({ })in the if…else statement will improve the readability.

59

Validating the Mortgage Payment Calculator Form

Validating Data Criteria Using Built-in FunctionsJavaScript accepts data entered into a text box as string data. If we want to using the information to do mathematics and comparison, we have to convert the values to a proper data type.

eval attempts to evaluate a string representing any JavaScript literals or variables, converting it to a number.

parseInt converts a string to an integer of the specified radix (base), if possible.

60

Validating the Mortgage Payment Calculator Form

parseFloat converts a string to a floating-point number, if possible.

The isNaN function evaluates an argument to determine if it is "NaN" (not a number).

61

Validating the Mortgage Payment Calculator Form

62

Validating the Mortgage Payment Calculator Form

We use the Calc() user defined function to convert and store the information inputted.

63

Validating the Mortgage Payment Calculator Form

Validate moreAmount

64

Validating the Mortgage Payment Calculator Form

Validate moreRate

65

Validating the Mortgage Payment Calculator Form

Validate moreYears

66

Validating the Mortgage Payment Calculator Form

67

Validating the Mortgage Payment Calculator Form

Adding an Event Handler to Call a Function

<INPUT Type="Button" value="Calculate" onclick="Calc(MortCalc)">

68

Validating the Mortgage Payment Calculator Form

Testing the Web page

69

Validating the Mortgage Payment Calculator Form

70

Determining the Monthly Payment

After validating all the inputted information, we want to use the information to generate the monthly payment. We will define a function monthly() which pass in mortAmount, mortRate, and mortYears to the function and return a monthly payment. The return information will assignment to document.MortCalc.Payment.value. So, we will insert the following statement in the Calc() function.

document.MortCalc.Payment.value=monthly(mortAmount,mortRate,mortYears)

71

Determining the Monthly Payment

72

Determining the Monthly Payment

Creating the monthly() FunctionThe formula to calculate the monthly payment of a loan is :

Monthly Interest Rate(MIR)Loan Amount * ( ) 1 (1-( ) (1 + MIR) payments

73

Determining the Monthly Payment

Creating the monthly() FunctionThe formula to calculate the monthly payment of a loan is :

Monthly Interest Rate(MIR)Loan Amount * ( ) 1 (1-( ) (1 + MIR) payments

74

Determining the Monthly Payment

Math.pow() method

We will use Math.pow() method to calculate the (1 + MIR) payments.

75

Determining the Monthly Payment

The whole function should look like the following:

76

Determining the Monthly Payment

77

Determining the Monthly Payment

78

Formatting the Monthly Payment Output as Currency

There are five steps we need to go through to format the currency:

1). Take the monthly payment dollar string value and separate the dollars from the cents based on the position of the decimal point.

2). Using the indexOf() method to determine the decimal point location.

3). Separate the value to dollar amount and cents amount by using the decimal point.

79

Formatting the Monthly Payment Output as Currency

4). Insert commas to the dollar amount for every three position.

5). Insert a dollar sign at the beginning of the string and concatenate it with the dollar amount, a decimal point and two digits of cents information and return the value.

80

Formatting the Monthly Payment Output as Currency

We put these steps into a function called dollarFormat(). This function need to pass in an argument, monthly payment amount, and will return a structured currency format.

function dollarFormat(valuein)

81

Formatting the Monthly Payment Output as Currency

indexOf Method. Returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex.

Syntax stringName.indexOf(searchValue, [fromIndex])

Parameters stringName is any string or a property of an existing object.

searchValue is a string or a property of an existing object, representing the value to search for.

82

Formatting the Monthly Payment Output as Currency

fromIndex is the location within the calling string to start the search from. It can be any integer from zero to stringName.length - 1 or a property of an existing object.

Description Characters in a string are indexed from left to right. The index of the first character is zero, and the index of the last character is stringName.length - 1.

If you do not specify a value for fromIndex, JavaScript assumes zero by default. If searchValue is not found, JavaScript returns -1.

83

Formatting the Monthly Payment Output as Currency

If stringName contains an empty string (""), indexOf returns an empty string.

The indexOf method is case sensitive. For example, the following expression returns -1: "Blue Whale".indexOf("blue")

Examplevar anyString="Brave new world"

//Displays 8document.write("<P>The index of the first w from the beginning is " +   anyString.indexOf("w"))

84

Formatting the Monthly Payment Output as Currency

//Displays 6document.write("<P>The index of 'new' from the beginning is " +  anyString.indexOf("new"))

85

Formatting the Monthly Payment Output as Currency

86

Formatting the Monthly Payment Output as Currency

Determining the Dollars Portion

87

Formatting the Monthly Payment Output as Currency

for loop

A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. A for statement looks as follows:

for ([initial-expression]; [condition]; [increment-expression]) {   statements}

88

Formatting the Monthly Payment Output as Currency

When a for loop executes, the following occurs:

1. The initializing expression initial-expression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity.

2. The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates.

89

Formatting the Monthly Payment Output as Currency

3. The update expression increment-expression executes.

4. The statements execute, and control returns to step 2.

Example. The following function contains a for statement that counts the number of selected options in a scrolling list (a Select object that allows multiple selections). The for statement declares the variable i and initializes it to zero.

90

Formatting the Monthly Payment Output as Currency

It checks that i is less than the number of options in the Select object, performs the succeeding if statement, and increments i by one after each pass through the loop. <SCRIPT>function howMany(selectObject) {          var numberSelected=0          for (var i=0; i < selectObject.options.length; i++) {                    if (selectObject.options[i].selected==true)                              numberSelected++          }          return numberSelected}</SCRIPT>

91

Formatting the Monthly Payment Output as Currency

92

Formatting the Monthly Payment Output as Currency

93

Formatting the Monthly Payment Output as Currency

while statementA while statement repeats a loop as long as a specified condition evaluates to true. A while statement looks as follows:

while (condition) {          statements}

If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop.

94

Formatting the Monthly Payment Output as Currency

The condition test occurs only when the statements in the loop have been executed and the loop is about to be repeated. That is, the condition test is not continuous but is performed once at the beginning of the loop and again just following the last statement in statements, each time control passes through the loop. Example. The following while loop iterates as long as n is less than three: n = 0x = 0while( n < 3 ) {          n ++          x += n}

95

Formatting the Monthly Payment Output as Currency

96

Formatting the Monthly Payment Output as Currency

Extracting the Dollars Portion and Inserting Commas

97

Formatting the Monthly Payment Output as Currency

Extracting the Cents Portion and Defining the Decimal Amount

substring Method. Returns a subset of a String object.

Syntax stringName.substring(indexA, indexB)

Parameters stringName is any string or a property of an existing object.

98

Formatting the Monthly Payment Output as Currency

indexA is any integer from zero to stringName.length - 1, or a property of an existing object.

indexB is any integer from zero to stringName.length, or a property of an existing object.

Method of String

99

Formatting the Monthly Payment Output as Currency

Description Characters in a string are indexed from left to right. The index of the first character is zero, and the index of the last character is stringName.length - 1.

If indexA is less than indexB, the substring method returns the subset starting with the character at indexA and ending with the character before indexB.

If indexA is greater than indexB, the substring method returns the subset starting with the character before indexB and ending with the character at indexA.

If indexA is equal to indexB, the substring method returns the empty string.

100

Formatting the Monthly Payment Output as Currency

Examples

The following examples use substring to display characters from the string "Netscape":

var anyString="Netscape" //Displays "Net" document.write(anyString.substring(0,3)) document.write(anyString.substring(3,0))

//Displays "cap" document.write(anyString.substring(4,7)) document.write(anyString.substring(7,4))

101

Formatting the Monthly Payment Output as Currency

//Displays "Netscap" document.write(anyString.substring(0,7))

//Displays "Netscape" document.write(anyString.substring(0,8)) document.write(anyString.substring(0,10))

102

Formatting the Monthly Payment Output as Currency

Extracting the Cents Portion and Defining the Decimal Amount

103

Formatting the Monthly Payment Output as Currency

Reconstructing the Formatted Output and Returning the Formatted Value

104

Formatting the Monthly Payment Output as Currency

105

Formatting the Monthly Payment Output as Currency

Passing the Monthly Payment Value to the dollarFormat() Function

106

Formatting the Monthly Payment Output as Currency

107

Adding a Pop-up Window

Except alert and confirm message boxes, we can use JavaScript (window object ‘s open())to open another HTML file to create a pop-up window.

108

Adding a Pop-up Window

open()’s attributes.

109

Adding a Pop-up Window

110

Adding a Pop-up Window

111

Adding a Pop-up Window

Adding the Date Last Modified