Client-Side Web Application Development with JavaScript

64
Client-Side Web Application Development with JavaScript ISYS 350

description

Client-Side Web Application Development with JavaScript. ISYS 350. Types of Web pages. Static page: The contents of a web page is predefined by HTML tags and other mark up languages. Example: david chao’s home page. Dynamic page - PowerPoint PPT Presentation

Transcript of Client-Side Web Application Development with JavaScript

Page 1: Client-Side Web Application Development with JavaScript

Client-Side Web Application Development with JavaScript

ISYS 350

Page 2: Client-Side Web Application Development with JavaScript

Types of Web pages

• Static page:– The contents of a web page is predefined by

HTML tags and other mark up languages.• Example: david chao’s home page.

• Dynamic page– A web page includes contents produced by a

programming language when the page is opened.

– Examples: • Pages that display current date/time, visitor counter

– Yahoo home page• Pages that display results based on a database query.

– Yahoo’s Finance/Enter symbol/Historical prices

Page 3: Client-Side Web Application Development with JavaScript

Technologies for Creating Dynamic Pages

• Client-side technology– HTML and Browser Document Object Model

(DOM) – JavaScript

• Server-side technology– Microsoft .Net– PHP– Java– Others

Page 4: Client-Side Web Application Development with JavaScript

Example of Client-side Page using HTML, DOM and JavaScript

Page 5: Client-Side Web Application Development with JavaScript

HTML Introduction

• History:– http://en.wikipedia.org/wiki/HTML

• Standard– The World Wide Web Consortium (W3C)

• HTML 5: <!DOCTYPE html> – Multimedia controls

• Video, audio, canvas

Page 6: Client-Side Web Application Development with JavaScript

Online Resources for Learning HTML

• w3schools.com – http://www.w3schools.com/default.asp

Page 7: Client-Side Web Application Development with JavaScript

HTML Tags (Elements)

• Heading section– <head>, <title>, <meta>, <script>, etc.

• Body section– <body>, <p>, <h1> to <h6>, <a>, <br>– Formatting: <b>, <I>, <u>, <center>– Comment: <!-- comment -->– List <ul>– Image– Table: <table>, <tr>: a new row in table, <td>: a new cell in

a table row.– Form: <form>, <input>, <select>

Page 8: Client-Side Web Application Development with JavaScript

HTML Attributes• HTML elements can have attributes that provide

additional information about an element.• Attributes are always specified in the start tag• Attributes come in name/value pairs like:

name="value“• Name and value are case-sensitive and lowercase is

recommended.

Page 9: Client-Side Web Application Development with JavaScript

TABLE Tag<table id=“depTable“ border="1" width=“400"> <thead>

<tr><th>Year</th>

<th>Value at BeginYr</th><th>Dep During Yr</th>

<th>Total to EndOfYr</th> </tr> </thead> <tbody>

<tr> <td>1</td> <td>2000</td> <td>400</td> <td>400</td> </tr> </tbody></table>

Page 10: Client-Side Web Application Development with JavaScript

FORM Tag

• Form attributes:– action: Specify the URL of a program on a server or an

email address to which a form’s data will be submitted.– method:

• Get: the form’s data is appended to the URL specified by the Action attribute as a QueryString.

• Post: A preferred method for database processing. Form’s data is sent in the HTTP body.

– mame: Form’s name

Page 11: Client-Side Web Application Development with JavaScript

QueryString

• A QueryString is a set of name=value pairs appended to a target URL.

• It can be used to pass information from one webpage to another.

• Example:– http://my.com/Target.htm?CustID=C1&Cname=Chao

Page 12: Client-Side Web Application Development with JavaScript

Adding HTML ControlsTools/Palette/HTML, JSPCode Clips

Page 13: Client-Side Web Application Development with JavaScript

Creating HTML Form: Double-click Form element

Page 14: Client-Side Web Application Development with JavaScript

Create a Form Using NetBean

Page 15: Client-Side Web Application Development with JavaScript

Step by Step• 1. Add a form tag:

– Name property– Action: server-side program; leave it blank for client-side

• 2. Add lables by typing• 3. Add text input • 4. Add dropdown list:

– Number of options

• 5. Add radiobutton– All buttons belong to a group

• 6. Add button– Lable– Type:

• Submit – submit to a server• Standard – client-side

• 7. Add <br> to start a new line

Page 16: Client-Side Web Application Development with JavaScript

Dropdown List Example

<select name="Rate"> <option value=.04>4%</option> <option value=045>4.5%</option> <option value=.05 >5%</option> <option value=.055>5.5%</option> <option value=.06>6%</option> </select>

Page 17: Client-Side Web Application Development with JavaScript

RadioButton Example:RadioButtons having the same name

belong to one group

<input type="radio" name="Year" value=10 />10 year<<br><input type="radio" name="Year" value=15 />15 year<br><input type="radio" name="Year" value=30 />30 year<br>

Page 18: Client-Side Web Application Development with JavaScript

<form name="fvForm" action=""> Enter PV: <input id='PV' type="text" name="PV" value="" /><br> Select Rate: <select name="Rate"> <option value=0.04>4%</option> <option value=0.045>4.5%</option> <option value=0.05>5%</option> <option value=0.055>5.5%</option> <option value=0.06>6%</option> <option value=0.065>6.5%</option> <option value=0.07>7%</option> </select><br> Select Year: <br> <input type="radio" name="Year" value=10 />10 year<br> <input type="radio" name="Year" value=15 />15 year<br> <input type="radio" name="Year" value=30 />30 year<br> <br> Future Value: <input type="text" name="FV" /> <br> <input type="button" value="ComputeFV" name="btnCompute" onClick="ComputeFV()" /> </form>

Note: We can assign an id to a HTML tag (element).

Page 19: Client-Side Web Application Development with JavaScript

HTML Tags and Events

• Link <a> </a>: click, mouseOver, mouseOut• Image <img>: abort(loading is interrupted), error,

load.• Area <area>: mouseOver, mouseOut• Body <body>: blur, error, focus, load, unload• Frameset: blur, error, focus, load, unload• Frame: blur, focus• Form: submit, reset• Textbox, Text area: blur, focus, change, select• Button, Radio button, check box: click• List: blur, focus, change

Page 20: Client-Side Web Application Development with JavaScript

Event Handler

• Event handler name: on + event name– Ex. onClick

• Calling a handler:– onClick="CompSumJS()“– onClick="window.alert('you click me')"

– Note: single quote/double quote

Page 21: Client-Side Web Application Development with JavaScript

Example of Event Handler<script > <!--function showSum(){ num1=parseFloat(window.prompt("Enter Num1: ")); num2=parseFloat(window.prompt("Enter Num2: ")); sum=num1+num2; window.alert("The sum is: " + eval(num1+num2)); window.alert("The sum is: " + sum);}--></script> </head> <body> <form name="testText"> <input type="text" id="text1" name="test" /> <input type="button" value="showTest" name="btnTest" onClick="showSum()"/> </form> </body>

Page 22: Client-Side Web Application Development with JavaScript

Browser Object Modelhttp://w3schools.com/jsref/default.asp

N a v ig a to r L o ca tion

T e xt

R a d io

C h e ckB ox , e tc

F o rm co lle c tion

Im a ge

L ink

A n ch o r, e tc

O th e r co llec tio ns

D o cum e nt H is to ry F ra m e

W in d ow

Page 23: Client-Side Web Application Development with JavaScript

Window Object• The Window object represents a Web browser window.• Properties:

– window.status, window.defaultstatus– window.document, window.history, window.location.– Window.name

• Methods:– window.open (“url”, “name”, Options)

• Options: menubar=no, status=no, toolbar=no, etc.– window.close– window.alert(“string”)– window.prompt(“string”)– Window.focus, Etc.

• Try statements at: http://w3schools.com/jsref/default.asp

Page 24: Client-Side Web Application Development with JavaScript

Navigator Object

• The navigator object provides information about the browser.

• Properties:– Navigator.appName:browser name– Navigator.appCodeName: browser code name– Navigator.appVersion– Navigator.platform: the operating system in use.

Page 25: Client-Side Web Application Development with JavaScript

Location Object

• Allows you to change to a new web page from within a script code.

• Properties:– Host, hostname, pathname– Href: current page’s URL address

• To reload a page:– location.reload()

• To open a page: Assign()– Ex. location.assign(URL)

Page 26: Client-Side Web Application Development with JavaScript

Testing<html>

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script>

function openNew(){

site=window.prompt("enter url:");

window.open (site);

location.assign("http://localhost:8080/WebApplication5");

}

</script>

</head>

<body>

<p><input type="button" value="Button" name="B3" onclick="openNew()"></p>

</body>

</html>

Page 27: Client-Side Web Application Development with JavaScript

History Object

• Maintain a history list of all the documents that have been opened during current session.

• Methods:– history.back()– history.forward()– history.go(): ex. History.go(-2)

Page 28: Client-Side Web Application Development with JavaScript

Document Object

• The document object represents the actual web page within the window.

• Properties: – background, bgColor, fgColor, title, url, lastModified,

domain, referrer, cookie, linkColor, etc. • Ex. document.bgColor=“silver”;

• Methods: – Document.write (“string”)– Document.open, close

Page 29: Client-Side Web Application Development with JavaScript

Accessing data entered on a form• Using the future value form as an example:

– Form name: fvForm– Textbox name: PV– Dropdown list: Rate– Radiobutton group name: Year

Page 30: Client-Side Web Application Development with JavaScript

Accessing data entered on a form• Textbox:

– document.fvForm.PV.value

• Dropdown list:– document.fvForm.Rate.options[document.fvForm.R

ate.selectedIndex].value

• Radiobuttons:if (document.fvForm.Year[0].checked) {myYear=10;}else if (document.fvForm.Year[1].checked) {myYear=15;}else {myYear=30;}

Page 31: Client-Side Web Application Development with JavaScript

CheckBox

document.LoanForm.checkBox1.checked

Page 32: Client-Side Web Application Development with JavaScript

Alternative way using the id attribute

document.getElementById(“PV").value

Page 33: Client-Side Web Application Development with JavaScript

JavaScript Reference

• http://w3schools.com/js/default.asp

Page 34: Client-Side Web Application Development with JavaScript

Client Side Script

• <script>• ……• ..statements• </script>

Page 35: Client-Side Web Application Development with JavaScript

JavaScript Variable Declaration

• var intrate, term, amount;• Data Type:

– Variant - a variable’s data type is determined when it is initialized to its first value.

• Variable scope:– Local: Variables declared in a function or procedure.– Global: Variables declared in the heading section, but not in

a function or procedure.

• Variable name is case-sensitive.• Note: We can use a variable without declare it.

Page 36: Client-Side Web Application Development with JavaScript

Statements

• Statements:– End with “;”– Block of code: { }

• Comments:– Single-line comment: //comment– Block comment:

• /* comment comment */

Page 37: Client-Side Web Application Development with JavaScript

Arrays

• var arrayName = new Array(array size);• var Pet = new Array(2);• Pet[0]=“dog”;• Pet[1]=“cat”;• Pet[2]=“bird”;

Page 38: Client-Side Web Application Development with JavaScript

Operators

• Arithmetic operators:+, -, *, /Math.pow(x,y), etc.

• Math is an object with many methods such as round(x), random(), sqrt(x), ceil(x), floor(x), etc.

• Note: “pow” has a lowercase p.

• Comparison operators:= = , !=, <, >, <=, >=

• Logical operators:&&, ||, !

Page 39: Client-Side Web Application Development with JavaScript

Formula to Expression

AB

B

A

Y

X

Math.pow(A,B) Math.pow(X/Y,A/B)

Page 40: Client-Side Web Application Development with JavaScript

IF StatementsJS: if (condition) {

statements;}else {

statements;}

if (document.fvForm.Year[0].checked) {myYear=10;}else if (document.fvForm.Year[1].checked) {myYear=15;}else {myYear=30;}

Page 41: Client-Side Web Application Development with JavaScript

Switch Case Statementsswitch(varable name) {case value1:

statements;break;

case value2:statements;break;

…default:

statements;break;

}

Page 42: Client-Side Web Application Development with JavaScript

Loop Structures1. while (condition) {

statements;}

2. for (var I = 0; I<5;I=I+1){statements;

}

Note: Use Break statement to exit loop earlier.Ex. Break ;

Page 43: Client-Side Web Application Development with JavaScript

JavaScript’s Conversion Functions• parseFloat:for conversion to a floating-point number:

– Ex. parseFloat('77.3') -> 77.3

• parseInt: for string-to-integer conversion– Ex. parseInt('123.45') -> 123

• toString(), toFixed(n) example:• Price=5;• Qty=10;• Amount=Price*Qty;• Document.write (Amount.toString());• Document.write (Amount.toFixed(2));

• eval• strVar = “5”;• numVar = eval(strVar)• Eval(Price*Qty)

Page 44: Client-Side Web Application Development with JavaScript

Try Catch

try { //Run some code here } catch(err) { //Handle errors here }

Page 45: Client-Side Web Application Development with JavaScript

window.prompt: similar to VB’s inputBoxwindow.alert: like MessageBox

function showSum(){ num1=parseFloat(window.prompt("Enter Num1: ")); num2=parseFloat(window.prompt("Enter Num2: ")); sum=num1+num2; window.alert("The sum is: " + eval(num1+num2)); window.alert("The sum is: " + sum);}

Page 46: Client-Side Web Application Development with JavaScript

JavaScript Functions

• Defining functions– function functionName(arg1,..,argN){

• Statements;• return return value;

– }

Note: 1. The arguments are optional.2. The return statement is optional. A JavaScript function is

not required to return a value.

Page 47: Client-Side Web Application Development with JavaScript

Example: JavaScript to Compute the sum of two values

<script ><!--function ComputeSum(){n1=document.testForm.num1.value;n2=document.testForm.num2.value;document.testForm.valueSum.value=eval(n1)+eval(n2);}--></script>

Page 48: Client-Side Web Application Development with JavaScript

JavaScript to compute the future value

Page 49: Client-Side Web Application Development with JavaScript

<form name="fvForm" action=""> Enter PV: <input id='PV' type="text" name="PV" value="" /><br> Select Rate: <select name="Rate"> <option value=0.04>4%</option> <option value=0.045>4.5%</option> <option value=0.05>5%</option> <option value=0.055>5.5%</option> <option value=0.06>6%</option> <option value=0.065>6.5%</option> <option value=0.07>7%</option> </select><br> Select Year: <br> <input type="radio" name="Year" value=10 />10 year<br> <input type="radio" name="Year" value=15 />15 year<br> <input type="radio" name="Year" value=30 />30 year<br> <br> Future Value: <input type="text" name="FV" /> <br> <input type="button" value="ComputeFV" name="btnCompute" onClick="ComputeFV()" /> </form>

Note: We can assign an id to a HTML tag (element).

Page 50: Client-Side Web Application Development with JavaScript

<script><!--function ComputeFV(){//myPV=eval(document.fvForm.PV.value);myPV=parseFloat(document.fvForm.PV.value);//myRate=eval(document.fvForm.Rate.options[document.fvForm.Rate.selectedIndex].value);myRate=parseFloat(document.fvForm.Rate.options[document.fvForm.Rate.selectedIndex].value);if (document.fvForm.Year[0].checked) {myYear=10;}else if (document.fvForm.Year[1].checked) {myYear=15;}else {myYear=30;}fv=myPV*Math.pow(1+myRate,myYear);document.fvForm.FV.value=fv.toString();}--></script>

Code Example

Page 51: Client-Side Web Application Development with JavaScript

Using document.getElementById<form name="fvForm"> Enter PV: <input type="text" id ="PV" name="PV" value="" size="10" /><br> <select name="Rate" id="Rate"> <option value=".04">4%</option> <option value=".05">5%</option> <option value=".06">6%</option> <option value=".07">7%</option> <option value=".08">8%</option> </select><br> Select Year: <br> <input type="radio" name="Year" value=10 id="Year10" />10 year<br> <input type="radio" name="Year" value=15 id="Year15" />15 year<br> <input type="radio" name="Year" value=30 id="Year30" />30 year<br> <br> Future Value: <input type="text" name="FV" /> <br> <input type="button" value="ComputeFV" name="btnCompute" onClick="ComputeFV()" />

Page 52: Client-Side Web Application Development with JavaScript

function ComputeFV(){//myPV=eval(document.fvForm.PV.value);myPV=parseFloat(document.getElementById("PV").value);myRate=parseFloat(document.getElementById("Rate").value);if (document.getElementById("Year10").checked) {myYear=10;}else if (document.getElementById("Year15").checked) {myYear=15;}else {myYear=30;}fv=myPV*Math.pow(1+myRate,myYear);document.fvForm.FV.value=fv.toString();}

Page 53: Client-Side Web Application Development with JavaScript

Years to Reach Goal

Page 54: Client-Side Web Application Development with JavaScript

Code Example<script type="text/javascript"><!--function ComputeJS(){pv=eval(document.testForm.txtPv.value);rate=eval(document.testForm.txtRate.value);goal=eval(document.testForm.txtGoal.value);fv=0;for (i=1; i<=9999; ++i){ fv=pv*Math.pow(1+rate,i); if(fv>=goal){ document.testForm.yearNeeded.value=i; break; } }

}--></script>

Page 55: Client-Side Web Application Development with JavaScript

Using while loop

year=0;while (fv<goal) { year=year+1; fv=pv*Math.pow(1+rate,year); if(fv>=goal)

{ document.testForm.yearNeeded.value=year; break; } }

Page 56: Client-Side Web Application Development with JavaScript

Working with TableStraight Line Depreciation Table

Page 57: Client-Side Web Application Development with JavaScript

HTML Table Tag

• <Table> : id and name attributes– <thead>: Table Heading section

• <tr>: new row– <th>: column heading

– <tbody>: data rows

Page 58: Client-Side Web Application Development with JavaScript

HTML Form Code<body> Straight Line Depreciation Table <form name="depForm"> Enter Property Value: <input type="text" name="pValue" value="" /><br> Enter Property Life: <input type="text" name="pLife" value="" /><br> <input type="button" value="Show Table" name="btnShowTable" onclick="showTable()" /> </form> <table id="depTable" border="1" width="400" cellspacing="1"> <thead> <tr> <th>Year</th> <th>Value at BeginYr</th> <th>Dep During Yr</th> <th>Total to EndOfYr</th> </tr> </thead> <tbody> </tbody> </table> </body>

Page 59: Client-Side Web Application Development with JavaScript

Table/Row/Cell Object• Table object:

– Properties:• rows: collection of data rows (including the header row)

– rows.length: number of rows– 0-based index

– Methods:• InsertRow(index)• deleteTow(index)

• Data Row object method:– insertCell(index)

• Cell object:– innerHTML property: cell’s data

Page 60: Client-Side Web Application Development with JavaScript

HTML element’s innerHTML property

• Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, you can make much more interactive pages.

• Assigning a value:– document.getElementById(“p”).innerHTML = 5;

Page 61: Client-Side Web Application Development with JavaScript

function showTable(){value=eval(document.depForm.pValue.value);life=eval(document.depForm.pLife.value);depreciation = value / life;var table = document.getElementById('depTable'); var totalDepreciation=0;

for(var i = table.rows.length - 1; i > 0; i--){ table.deleteRow(i);}for (count = 1; count <= life; count++) { var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell0 = row.insertCell(0); cell0.innerHTML=count; var cell1 = row.insertCell(1); cell1.innerHTML="$" + value.toFixed(2); var cell2 = row.insertCell(2); cell2.innerHTML="$" + depreciation.toFixed(2); totalDepreciation += depreciation; var cell3 = row.insertCell(3); cell3.innerHTML="$" + totalDepreciation.toFixed(2); value -= depreciation;} }

Page 62: Client-Side Web Application Development with JavaScript

Validating Data: The property value and life boxes cannot be blank

<script ><!--function Validating(){var Valid;Valid=true;if (document.depForm.pValue.value=="" ||document.depForm.pLife.value=="") {Valid=false;}

if (Valid==false) {alert("Property value or life cannot contain blank");}else {showTable();}}--></script>

Note: the button’s onClick event will call the Validating function:<input type="button" value="Show Table" name="btnShowTable" onclick="Validating()" />

Page 63: Client-Side Web Application Development with JavaScript

Useful function for Validation

• isNaN(): The isNaN() function determines whether a value is an illegal number (Not-a-Number). This function returns true if the value is NaN, and false if not.

Page 64: Client-Side Web Application Development with JavaScript

isNaN examplefunction Validating(){var Valid, Valid2;Valid=true;Valid2=true;

if (document.depForm.pValue.value=="" ||document.depForm.pLife.value=="") {Valid=false;}if (isNaN(document.depForm.pValue.value) ||isNaN(document.depForm.pLife.value)) {Valid2=false;} if (Valid==false) {alert("Property value or life cannot contain blank");}if (Valid2==false) {alert("Enter digits only");} if (Valid && Valid2) { showTable(); }}