+ All Categories
Home > Documents > Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven...

Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven...

Date post: 17-Jan-2016
Category:
Upload: patrick-newton
View: 215 times
Download: 1 times
Share this document with a friend
44
Client-Side programming with JavaScript 2
Transcript
Page 1: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Client-Side programming with JavaScript 2

Page 2: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Event-driven programs and HTML form elements

Event-driven programs and HTML form elements

event-driven programsonload, onunload

HTML forms & attributesbutton, text box, text areaselection list, radio button, check box, password, hidden,

… JavaScript form events

properties: name, type, value, …methods: blur(), focus(), click(), …event handlers: onblur(), onfocus(), onchange(),

onclick(), … advanced features & techniques

windows & frames, timeouts, cookies

Page 3: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Event-driven programs

• Computation within a Web page is rarely serial instead, the page reacts to events such as mouse clicks, buttons, … much of JavaScript's utility is in specifying actions that

are to occur in the page as a result of some event

the programmer may have little or no control over when code will (if ever) be executed, e.g., code that reacts to a button click

there is no set sequence, the page waits for events and reacts

Page 4: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

OnLoad & OnUnload

•the simplest events are when the page is loaded or unloaded

–the onload attribute of the <body> tag specifies JavaScript code that is automatically executed when the page is loaded

–the onunload attribute similarly specifies JavaScript code that is automatically executed when the browser leaves the page

Page 5: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

<html> <head> <title>Hello/Goodbye page</title>

<script type="text/javascript"> function Hello() { globalName=prompt("Welcome to my page. " +"What is your name?",""); }

function Goodbye() { alert(“Goodbye, " + globalName + " come back real soon."); } </script> </head>

<body onload="Hello();" onunload="Goodbye();"> Whatever text appears in the page. </body></html>

view page

Page 6: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

HTML forms• most event-handling in JavaScript is associated with form

elements

• an HTML form is a collection of elements for handling input, output, and events in a page

<form name="FormName">

</form>

form elements might include:

for input: button, selection list, radio button, check box, password, …

for input/output: text box, text area, …

Page 7: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Button Element

• the simplest form element is a button

–analogous to a real-world button, a click can be used to trigger events

<input type="button" value="LABEL" onclick="JAVASCRIPT_CODE"/>

Page 8: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

<html> <head> <title> Fun with Buttons</title>

<script type="text/javascript“ src="random.js"> </script> </head>

<body> <form name="ButtonForm"> <input type="button" value="Click for Lucky Number" onclick= “var num = RandomInt(1, 100);alert('The lucky number for the day is ' + num);" > </form> </body></html>

view page

Page 9: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Buttons & Functions

<html> <head> <title>Fun with Buttons</title>

<script type="text/javascript"> function Greeting() // Results: displays a time-sensitive greeting { var now = new Date(); if (now.getHours() < 12) { alert("Good morning"); } else if (now.getHours() < 18) { alert("Good afternoon"); } else { alert("Good evening"); } } </script> </head>

for complex tasks, should define function(s) and have the onclick event trigger a function call

Page 10: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

<body> <form name="ButtonForm"> <input type="button" value="Click for Greeting" onclick="Greeting();" > </form> </body></html>

view page

Page 11: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Text Boxes• a text box allows for user input

– unlike prompt, user input persists on the page & can be edited

<input type="text" name=“UserName"… />

optional attributes: size : width of the box (number of characters)value : initial contents of the boxMaxlength: Specify the maximum input length

JavaScript code can access the contents as document.BoxForm.userName.value

Page 12: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Text Boxes<html> <head> <title> Fun with Text Boxes </title> </head>

<body> <form name="BoxForm"> Enter your name here: <input type="text" name="userName" size=“12” value="" > <br /><br /> <input type="button" value="Click Me" onclick="alert('Thanks, ' + document.BoxForm.userName.value + ', I needed that.');" > </form> </body></html>

view page

Page 13: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Read/Write Text Boxes

• similarly, can change the contents with an assignment

Note: the contents are raw text, no HTML formatting

Also: contents are accessed as a string, must parseFloat or parseInt if want a number

Page 14: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Read/Write Text Boxes<html> <head> <title> Fun with Text Boxes </title> </head>

<body> <form name="BoxForm"> Enter a number here: <input type="text" size=“12” name="number" value=“2” /> <br /><br /> <input type="button" value="Double" onclick="document.BoxForm.number.value= parseFloat(document.BoxForm.number.value) * 2;" /> </form> </body></html>

view page

Page 15: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Text Box Events

•onchange triggered when the contents of the box are changed

•onfocus triggered when the mouse clicks in the box

•blur() removes focus

Page 16: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

<html> <head> <title> Fun with Text Boxes </title> <script type="text/javascript"> function FahrToCelsius(tempInFahr) // Assumes: tempInFahr is a number //(degrees Fahrenheit) // Returns: corresponding temperature in //degrees Celsius { return (5/9)*(tempInFahr - 32); } </script> </head>

Text Box Events

Page 17: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Text Box Events

<body> <form name="BoxForm"> Temperature in Fahrenheit: <input type="text" name="Fahr" size=“10” value=“0" onchange="document.BoxForm.Celsius.value = FahrToCelsius(parseFloat(document.BoxForm.Fahr.value));" > &nbsp; ---- &nbsp; <input type="text" name="Celsius" size=“10” value="" onfocus="blur();" > in Celsius </form> </body></html> view page

Page 18: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Text Box Validation

• what if the user enters a non-number in the Fahrenheit box?

• solution: have the text box validate its own contents– start with legal value– at onchange, verify that new value is legal (otherwise,

reset)

– the verify.js library defines several functions for validating text boxes

Page 19: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Text Box Validation

function VerifyNum(textBox) // Assumes: textBox is a text box // Returns: true if textBox contains a number, else false + alert { var boxValue = parseFloat(textBox.value); if ( isNaN(boxValue) ) { // ** isNaN function alert("You must enter a number value!"); textBox.value = ""; return false; } return true; }

Page 20: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Validation Example<html> <head> <title> Fun with Text Boxes </title> <script type="text/javascript" src="verify.js"> </script>

<script type="text/javascript"> function FahrToCelsius(tempInFahr) { return (5/9)*(tempInFahr - 32); } </script> </head>

Page 21: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Validation Example

<body> <form name="BoxForm"> Temperature in Fahrenheit: <input type="text" name="Fahr" size=“10” value=“0” onchange="if (VerifyNum(this)) { // this refers to current element document.BoxForm.Celsius.value = FahrToCelsius(parseFloat(this.value)); }" > &nbsp; &nbsp; <input type="text" name="Celsius" size=“10” value="" onfocus="blur();" > in Celsius </form> </body></html>

view page

Page 22: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.
Page 23: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

OnSubmit

• The OnSubmit event is used to validate ALL form fields before submitting it.

<form method="post" action=“MMM.htm“onsubmit="return checkForm()">

The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled

Page 24: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

JavaScript indexOf() Method

• Definition and Usage

• The indexOf() method returns the position of the first occurrence of a specified string value in a string.

• Syntax– stringObject.indexOf(searchvalue)

• The indexOf() method is case sensitive!

Page 25: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Validation Example

<body>

<form action="submitpage.htm"

onsubmit="return validate_form(this)"

method="post">

Email: <input type="text" name="email" size="30">

<input type="submit" value="Submit">

</form>

</body>

Page 26: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Validation Example

• Required Fields:

function validate_required(field , alerttxt){with (field){if (value==null || value=="") {alert(alerttxt) return false}else {return true}}}

view page

Page 27: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

JavaScript Email Validation

function validate_form(thisform){with (thisform){ if (validate_required(email,"Email must be filled out!")==false) {email.focus() return false }}}

Page 28: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

JavaScript Email Validation

function validate_email(field , alerttxt){with (field) {apos=value.indexOf("@") dotpos=value.lastIndexOf(".") if (apos<1||dotpos-apos<2) { alert(alerttxt) return false }else {return true}}}

view page

Page 29: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

JavaScript Animation

<a href="http://www.Google.com" target="_blank“

onmouseOver="mouseOver()“onmouseOut="mouseOut()">

<img border="0" alt="Visit Google!"src="b_pink.gif" name="b1" />

</a>

Page 30: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

JavaScript Animation

<script type="text/javascript">function mouseOver(){document.b1.src ="b_blue.gif“}function mouseOut(){document.b1.src ="planets.gif “}</script>

view page

Page 31: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Text Areas

• a TEXT box is limited to one line of input/output

• a TEXTAREA is similar to a text box in functionality, but can specify any number of rows and columns

<textarea name="TextAreaName" rows=“NumRows” cols=“NumCols”>

Initial Text

</textarea>

Page 32: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Text Areas

–Note: unlike a text box, a TEXTAREA has a separate closing tag

•initial contents of the TEXTAREA appear between the tags

–as with a text box, no HTML formatting of TEXTAREA contents

Page 33: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

TEXTAREA Example<html> <head> <title> Fun with Textareas </title> <script type="text/javascript“ src="verify.js"> </script> <script type="text/javascript"> function Table(low, high, power) {// Results: displays table of numbers between low &

//high, raised to power var message = "i: i^" + power + "\n-------\n"; for (var i = low; i <= high; i++) { message = message + i + ": " + Math.pow(i, power) + "\n";

} document.AreaForm.Output.value = message; } </script> </head>

Page 34: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

<body> <form name="AreaForm"> <div style="text-align: center;"> Show the numbers from <input type="text" name="lowRange" size=“4” value=“1” onchange="VerifyInt(this);" /> to <input type="text" name="highRange" size=“4” value=“10” onchange="VerifyInt(this);" /> raised to the power of <input type="text" name="power" size=3 value=2 onchange="VerifyInt(this);" /> <br /> <br /> <input type="button" value="Generate Table" onClick="Table(parseFloat(document.AreaForm.lowRange.value), parseFloat(document.AreaForm.highRange.value), parseFloat(document.AreaForm.power.value));" /> <br /> <br /> <textarea name="Output" rows=“20” cols=“15”></textarea> </div> </form> </body></html>

view page

Page 35: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

• So far, we have been accessing data input fields by giving them names, and using the “dotted” names from the Document Object Model tree structure.

• What if someone modifies the HTML document?

• Then, all those multiply referenced items can no longer be accessed.

• A more reliable manner (more resistant to changes in the webpage code) would be to give each element an ID (using the “id” attibute) and use the JavaScript getElementById method.

Better (and easier?) methods to access data

Page 36: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Using getElementById<html> <head> <title> Fun with Text Boxes </title> <script type="text/javascript" src="verify.js"> </script>

<script type="text/javascript"> function FahrToCelsius(tempInFahr) { return (5/9)*(tempInFahr - 32); } </script> </head>

Page 37: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Using getElementById

<body> <form name="BoxForm"> Temperature in Fahrenheit: <input type="text" id="Fahr" size=“10” value=“0” onchange="if (VerifyNum(this)) { // this refers to current element var F=document.getElementById(‘Fahr’); document.BoxForm.Celsius.value = FahrToCelsius(parseFloat(F.value)); }" /> &nbsp; <tt>----></tt> &nbsp; <input type="text" name="Celsius" size=“10” value=“” onfocus=“getElementById(‘F’).focus();" /> in Celsius </form> </body></html>

view page

Page 38: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Check buttons<html> <head> <title> Check Boxes </title> <script type="text/javascript"> function processCB() {var boxes = document.BoxForm.cb.length; var s=""; for (var i = 0; i < boxes; i++) { if (document.BoxForm.cb[i].checked) { s = s + document.BoxForm.cb[i].value + " "; } } if (s == "") { s = "nothing"; } alert("You selected " + s); } </script> </head>

Page 39: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Check buttons<body> <form name="BoxForm"> Which of these things is unavoidable in life (select one or more):<br/><br/>&nbsp; <input type="checkbox" name="cb“ value="Death">Death</input><br/>&nbsp; <input type="checkbox" name="cb" value="Taxes">Taxes</input><br/> &nbsp; <input type="checkbox" name="cb" value=“Watching TV"> Watching TV </input><br> <br> <input type="button" value="Done" onclick="processCB()“ > </form> </body></html>

view page

Page 40: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Radio buttons

• Radio buttons are similar to check boxes, but only one of them can be selected at any time.

• They are defined by <input type=“radio”> tags (similar to the checkbox tags in the previous example, with similar properties) and accessed in the same manner.

view page

Page 41: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

JavaScript & Timeouts

• the setTimeout function can be used to execute code at a later time

setTimeout(JavaScriptCodeToBeExecuted, MillisecondsUntilExecution)

• example: forward link to a moved page

Page 42: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

<html> <head> <title> Fun with Timeouts </title> <script type="text/javascript"> function Move() // Results: sets the current page //contents to be newhome.html

{ self.location.href = "newhome.html"; } </script> </head>

<body onload="setTimeout('Move()', 3000);"> This page has moved to <a href="newhome.html">newhome.html</a>.

</body></html>

view page

Page 43: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

<html> <head> <title> Fun with Timeouts </title> <script type="text/javascript"> function timeSince() // Assumes: document.CountForm.countdown exists in the page // Results: every second, recursively writes current countdown

//in the box { // CODE FOR DETERMINING NUMBER OF DAYS, HOURS, MINUTES, AND //SECONDS // UNTIL GRADUATION (see the file for this code!!!)

document.CountForm.countdown.value= days + " days, " + hours + " hours, " + minutes + " minutes, and " + secs + " seconds";

setTimeout("timeSince();", 1000); } </script> </head>

Another Timeout Example

Page 44: Client-Side programming with JavaScript 2. Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes.

Another Timeout Example

<body onload="timeSince();"> <form name="CountForm"> <div style="text-align: center;"> Countdown to Graduation 2015 <br /> <textarea name="countdown" rows=“4” cols=“15” style="font-family: Courier;" onfocus="blur();"></textarea> </div> </form> </body></html>

view page


Recommended