slide1
Download
Skip this Video
Download Presentation
CS 21A

Loading in 2 Seconds...

play fullscreen
1 / 111

CS 21A - PowerPoint PPT Presentation


  • 158 Views
  • Uploaded on

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

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'CS 21A' - kass


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
slide1

CS 21A

  • Beginning JavaScript Programming

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

Sonny Huang

project 2 creating pop up windows adding scrolling messages and validating forms
Project 2 Creating Pop-up Windows, Adding Scrolling Messages, and Validating Forms
  • Outline
  • l  Explain the four basic components of a scrolling message
  • l 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
project 2 creating pop up windows adding scrolling messages and validating forms1
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
introduction
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.

introduction1
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.

introduction2
Introduction

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

Look for this web site homeadvisor.msn.comand otheronline lenders and realtors .

Do you search for a house online?

How do you feel about applying for loans online?

What are the important issues?

project two home finders nationwide realty
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.

project two home finders nationwide realty1
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.

project two home finders nationwide realty2
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.

project two home finders nationwide realty3
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.

project two home finders nationwide realty4
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.

project two home finders nationwide realty5
Project Two — Home Finders Nationwide Realty

Calculations:

The formula for calculating a monthly payment is

Monthly payment =

loan * rate

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

project two home finders nationwide realty6
Project Two — Home Finders Nationwide Realty

Starting Notepad and opening the home.htm file

inserting a scrolling message on a web page
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>

inserting a scrolling message on a web page1
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.

inserting a scrolling message on a web page2
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.)

inserting a scrolling message on a web page3
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 definitions

type = 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.

inserting a scrolling message on a web page4
Inserting a scrolling message on a Web page

size = number

This 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.

inserting a scrolling message on a web page5
Inserting a scrolling message on a Web page

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

inserting a scrolling message on a web page7
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

inserting a scrolling message on a web page8
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.

inserting a scrolling message on a web page10
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)

inserting a scrolling message on a web page11
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! --- ---

inserting a scrolling message on a web page12
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.

inserting a scrolling message on a web page13
Inserting a scrolling message on a Web page

Increment the Position Locator Variable

beginPos = beginPos + 1

inserting a scrolling message on a web page15
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, {}.

inserting a scrolling message on a web page18
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           }}

inserting a scrolling message on a web page19
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

}

inserting a scrolling message on a web page20
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

}

using the settimeout method to create a recursive function call
Using 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)

using the settimeout method to create a recursive function call2
Using the setTimeout() Method to create a Recursive Function Call

Adding an Event Handler

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

using the settimeout method to create a recursive function call4
Using the setTimeout() Method to create a Recursive Function Call

Insert the following statement

<BODY onload="scrollingMsg()">

the mortgage payment calculator form
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.

the mortgage payment calculator form1
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.).

the mortgage payment calculator form2
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.
the mortgage payment calculator form3
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>

the mortgage payment calculator form4
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>

writing the domort user defined function
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>

writing the domort user defined function1
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()

writing the domort user defined function2
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.

writing the domort user defined function3
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.

writing the domort user defined function4
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()

}

validating the mortgage payment calculator form1
Validating the Mortgage Payment Calculator Form

Validating Data Using the If… Else Statement

validating the mortgage payment calculator form3
Validating the Mortgage Payment Calculator Form

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

validating the mortgage payment calculator form4
Validating the Mortgage Payment Calculator Form

Validating Data Criteria Using Built-in Functions

JavaScript 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.
validating the mortgage payment calculator form5
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).
validating the mortgage payment calculator form7
Validating the Mortgage Payment Calculator Form

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

validating the mortgage payment calculator form12
Validating the Mortgage Payment Calculator Form

Adding an Event Handler to Call a Function

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

determining the monthly payment
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)

determining the monthly payment2
Determining the Monthly Payment

Creating the monthly() Function

The formula to calculate the monthly payment of a loan is :

Monthly Interest Rate(MIR)

Loan Amount * ( )

1

(1-( )

(1 + MIR) payments

determining the monthly payment3
Determining the Monthly Payment

Creating the monthly() Function

The formula to calculate the monthly payment of a loan is :

Monthly Interest Rate(MIR)

Loan Amount * ( )

1

(1-( )

(1 + MIR) payments

determining the monthly payment4
Determining the Monthly Payment

Math.pow() method

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

determining the monthly payment5
Determining the Monthly Payment

The whole function should look like the following:

formatting the monthly payment output as currency
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.

formatting the monthly payment output as currency1
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.

formatting the monthly payment output as currency2
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)

formatting the monthly payment output as currency3
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.

formatting the monthly payment output as currency4
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.

formatting the monthly payment output as currency5
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")

Example

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

formatting the monthly payment output as currency6
Formatting the Monthly Payment Output as Currency

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

formatting the monthly payment output as currency9
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}

formatting the monthly payment output as currency10
Formatting the Monthly Payment Output as Currency

When a for loop executes, the following occurs:

  • 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.
  • 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.
formatting the monthly payment output as currency11
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.

formatting the monthly payment output as currency12
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=0for (var i=0; i < selectObject.options.length; i++) {if (selectObject.options[i].selected==true)numberSelected++}return numberSelected}</SCRIPT>

formatting the monthly payment output as currency15
Formatting the Monthly Payment Output as Currency

while statement

A 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.

formatting the monthly payment output as currency16
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}

formatting the monthly payment output as currency18
Formatting the Monthly Payment Output as Currency

Extracting the Dollars Portion and Inserting Commas

formatting the monthly payment output as currency19
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.

formatting the monthly payment output as currency20
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

formatting the monthly payment output as currency21
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.
formatting the monthly payment output as currency22
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))

formatting the monthly payment output as currency23
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))

formatting the monthly payment output as currency24
Formatting the Monthly Payment Output as Currency

Extracting the Cents Portion and Defining the Decimal Amount

formatting the monthly payment output as currency25
Formatting the Monthly Payment Output as Currency

Reconstructing the Formatted Output and Returning the Formatted Value

formatting the monthly payment output as currency27
Formatting the Monthly Payment Output as Currency

Passing the Monthly Payment Value to the dollarFormat() Function

adding a pop up window
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.

adding a pop up window1
Adding a Pop-up Window

open()’s attributes.

adding a pop up window4
Adding a Pop-up Window

Adding the Date Last Modified

ad