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

Slides:



Advertisements
Similar presentations
Computer and Communication Fundamental Basic web programming Lecture 8 Rina Zviel-Girshin.
Advertisements

JavaScript Forms Form Validation Cookies. What JavaScript can do  Control document appearance and content  Control the browser  Interact with user.
Forms cs105. More Interactive web-pages So far what we have seen was to present the information. (Ex: tables. Lists,….). But it is not enough. We want.
Chapter 7 © 2001 by Addison Wesley Longman, Inc. 1 Chapter 7 Sebesta: Programming the World Wide Web.
JavaScript Forms Form Validation Cookies CGI Programs.
1 A Balanced Introduction to Computer Science, 2/E David Reed, Creighton University ©2008 Pearson Prentice Hall ISBN Chapter 7 Event-Driven.
Information Technology Center Hany Abdelwahab Computer Specialist.
COMP 519: Web Programming Autumn 2014 Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes.
CSC4370/6370: Web Programming Event-driven programs and HTML form elements  event-driven programs  onload, onunload  HTML forms & attributes  button,
CST JavaScript Validating Form Data with JavaScript.
1 Events Lect 8. 2 Event-driven Pages one popular feature of the Web is its interactive nature e.g., you click on buttons to make windows appear e.g.,
CP476 Internet Computing JavaScript and HTML1 1.JavaScript Execution Environment The JavaScript Window object represents the window in which the browser.
Client-Side programming with JavaScript 3
JS: DOM Form Form Object Form Object –The Form object represents an HTML form. –For each instance of a tag in an HTML document, a Form object is created.
Forms and Form Controls Chapter What is a Form?
HTML Forms/Events (Instructor Lesson) The Event model HTML Forms Custom Events 1.
CNIT 133 Interactive Web Pags – JavaScript and AJAX Event and Event Handling.
Introduction to JavaScript. JavaScript Facts A scripting language - not compiled but interpreted line by line at run-time. Platform independent. It is.
Chapter 5 Java Script And Forms JavaScript, Third Edition.
1 SEN 910 CSS/HTML Programming Final Exam Review.
Event-driven Programming
Event Handlers CS101 Introduction to Computing. Learning Goals Learn about event handlers Determine how events are useful in JavaScript Discover where.
WEEK 3 AND 4 USING CLIENT-SIDE SCRIPTS TO ENHANCE WEB APPLICATIONS.
Chapter 5 © 2003 by Addison-Wesley, Inc. 1 Chapter 5 JavaScript and HTML Documents.
Copyright ©2005  Department of Computer & Information Science Introducing DHTML & DOM: JavaScript & Forms.
Execution Environment for JavaScript " Java Script Window object represents the window in which the browser displays documents. " The Window object provides.
JavaScript II ECT 270 Robin Burke. Outline JavaScript review Processing Syntax Events and event handling Form validation.
JavaScript Part 1.
JavaScript Part 1.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Using Client-Side Scripts to Enhance Web Applications 1.
Introduction to JavaScript 41 Introduction to Programming the WWW I CMSC Winter 2004 Lecture 17.
JavaScript, Fourth Edition Chapter 5 Validating Form Data with JavaScript.
CO1552 Web Application Development HTML Forms, Events and an introduction to JavaScript.
1 Final Exam Review Web Programming with HTML and Java.
1 Website Development HTML Forms and JavaScript Event-driven programs and HTML form elements  event-driven programs  ONLOAD, ONUNLOAD  HTML forms &
Client side scripting - javascript Pertemuan 4 Matakuliah: Web Programming Tahun: 2009.
Document Objects Forms, Images and Links. The document object model Each element of an HTML document, such as an image, form, link, or button, can be.
Lecture 10 JavaScript: DOM and Dynamic HTML Boriana Koleva Room: C54
JavaScript - Basic Concepts Prepared and Presented by Hienvinh Nguyen, Afshin Tiraie.
Event JavaScript's interaction with HTML is handled through events that occur when the user or browser manipulates a page. When the page loads, that is.
Fluency with Information Technology INFO100 and CSE100 Katherine Deibel Katherine Deibel, Fluency in Information Technology1.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
Event Handling. Objectives Using event handlers Simulating events Using event-related methods.
Project 8: Reacting to Events Essentials for Design JavaScript Level One Michael Brooks.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Variables, Functions and Events (NON-Audio version) © Dr. David C. Gibbs WDMD.
HTML FORMS The TEXT Object Presented By: Ankit Gupta.
CSC 551: Web Programming Fall 2001 HTML forms & JavaScript events  HTML forms & attributes  button, text box, text area  selection list, radio button,
SEN 910 CSS/HTML Programming HTML Forms and JavaScript Event-driven programs and HTML form elements  event-driven programs  ONLOAD, ONUNLOAD  HTML forms.
1 CSC 551: Web Programming Spring 2004 Event-driven programs and HTML form elements  event-driven programs  ONLOAD, ONUNLOAD  HTML forms & attributes.
5 th and 4 th ed: some from chapters 9, 12, 13 SY306 Web and Databases for Cyber Operations Slide Set #8: Dynamic HTML.
JavaScript Event Handlers. Introduction An event handler executes a segment of a code based on certain events occurring within the application, such as.
LESSON : EVENTS AND FORM VALIDATION -JAVASCRIPT. EVENTS CLICK.
Event Handlers Events are asynchronous. When an event occurs, JavaScript can execute code in response to the user’s action. This response to the user-initiated.
CSC 121 Computers and Scientific Thinking Fall Event-Driven Programming.
Client-side (JavaScript) Validation. Associating a function with a click event – Part 1 Use the input tag’s onclick attribute to associate a function.
XHTML Forms.
Chapter 5 Validating Form Data with JavaScript
Event-Driven Programming
JavaScript and HTML Simple Event Handling 11-May-18.
In this session, you will learn to:
Forms Web Design Ms. Olifer.
JAVASCRIPTS AND HTML DOCUMENTS
JavaScript and HTML Simple Event Handling 19-Sep-18.
Event-driven programs and HTML form elements
Chapter 6 Event-Driven Pages
Chapter 7 Event-Driven Pages
JavaScript and Ajax (JavaScript Events)
JavaScript and HTML Simple Event Handling 26-Aug-19.
JavaScript and HTML Simple Event Handling 4-Oct-19.
Presentation transcript:

Client-Side programming with JavaScript 2

Event-driven programs and HTML form elements event-driven programs  onload, onunload  HTML forms & attributes  button, text box, text area  selection 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

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

OnLoad & OnUnload the simplest events are when the page is loaded or unloaded –the onload attribute of the 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

Hello/Goodbye page function Hello() { globalName=prompt("Welcome to my page. " +"What is your name?",""); } function Goodbye() { alert(“Goodbye, " + globalName + " come back real soon."); } Whatever text appears in the page. view page

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 elements might include: for input: button, selection list, radio button, check box, password, … for input/output: text box, text area, …

Button Element the simplest form element is a button –analogous to a real-world button, a click can be used to trigger events

Fun with Buttons <input type="button" value="Click for Lucky Number" onclick= “var num = RandomInt(1, 100); alert('The lucky number for the day is ' + num);" > view page

Buttons & Functions Fun with Buttons 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"); } for complex tasks, should define function(s) and have the onclick event trigger a function call

<input type="button" value="Click for Greeting" onclick="Greeting();" > view page

Text Boxes a text box allows for user input –unlike prompt, user input persists on the page & can be edited optional attributes: size : width of the box (number of characters) value : initial contents of the box Maxlength: Specify the maximum input length JavaScript code can access the contents as document.BoxForm.userName.value

Text Boxes Fun with Text Boxes Enter your name here: <input type="text" name="userName" size=“12” value="" > <input type="button" value="Click Me" onclick="alert('Thanks, ' + document.BoxForm.userName.value + ', I needed that.');" > view page

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

Read/Write Text Boxes Fun with Text Boxes Enter a number here: <input type="button" value="Double" onclick="document.BoxForm.number.value= parseFloat(document.BoxForm.number.value) * 2;" /> view page

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

Fun with Text Boxes function FahrToCelsius(tempInFahr) // Assumes: tempInFahr is a number //(degrees Fahrenheit) // Returns: corresponding temperature in //degrees Celsius { return (5/9)*(tempInFahr - 32); } Text Box Events

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

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

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; }

Validation Example Fun with Text Boxes <script type="text/javascript" src="verify.js"> function FahrToCelsius(tempInFahr) { return (5/9)*(tempInFahr - 32); }

Validation Example 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)); }" > <input type="text" name="Celsius" size=“10” value="" onfocus="blur();" > in Celsius view page

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

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!

Validation Example <form action="submitpage.htm" onsubmit="return validate_form(this)" method="post">

Validation Example Required Fields: function validate_required(field, alerttxt) { with (field) { if (value==null || value=="") {alert(alerttxt) return false} else {return true} } view page

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

JavaScript Validation function validate_ (field, alerttxt) { with (field) dotpos=value.lastIndexOf(".") if (apos<1||dotpos-apos<2) { alert(alerttxt) return false } else {return true} } view page

JavaScript Animation <a href=" target="_blank“ onmouseOver="mouseOver()“ onmouseOut="mouseOut()">

JavaScript Animation function mouseOver() { document.b1.src ="b_blue.gif“ } function mouseOut() { document.b1.src ="planets.gif “ } view page

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 Initial Text

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

TEXTAREA Example Fun with Textareas 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; }

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);" /> <input type="button" value="Generate Table" onClick="Table(parseFloat(document.AreaForm.lowRange.value), parseFloat(document.AreaForm.highRange.value), parseFloat(document.AreaForm.power.value));" /> view page

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

Using getElementById Fun with Text Boxes <script type="text/javascript" src="verify.js"> function FahrToCelsius(tempInFahr) { return (5/9)*(tempInFahr - 32); }

Using getElementById 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)); }" /> ----> <input type="text" name="Celsius" size=“10” value=“” onfocus=“getElementById(‘F’).focus();" /> in Celsius view page

Check buttons Check Boxes 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); }

Check buttons Which of these things is unavoidable in life (select one or more): Death Taxes Watching TV view page

Radio buttons Radio buttons are similar to check boxes, but only one of them can be selected at any time. They are defined by tags (similar to the checkbox tags in the previous example, with similar properties) and accessed in the same manner. view page

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

Fun with Timeouts function Move() // Results: sets the current page //contents to be newhome.html { self.location.href = "newhome.html"; } This page has moved to newhome.html. view page

Fun with Timeouts 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); } Another Timeout Example

Countdown to Graduation 2015 view page