var dom = document.getElementById("myForm")
for (index = 0; i < dom.planeButton.length; index++) {
dom.planeButton[index].onclick = planeChoice;
}
* This registration must happen after the handler function has been defined and when the HTML form has been loaded.
----
This works because form elements that have the same name are automatically coerced into a JavaScript array with that name.
To ensure correct assignment of even handlers, the script must either be the last thing that the browser loads or the execution of the registration code must be deferred until the document is ready.
===== Handling Events from Button Elements (continued) =====
* If this is done for a radio button group, each element of the array must be assigned
* In this case, the checked property of a radio button object is used to determine whether a button is clicked
===== Handling Events from Button Elements (continued) =====
* If the name of the buttons is ''planeButton'':
var dom = document.getElementById("myForm");
for (var index = 0;
index < dom.planeButton.length; index++) {
if (dom.planeButton[index].checked) {
plane = dom.planeButton[index].value;
break;
}
}
===== Example =====
* This is the same example used in the last lecture. This time we register the event handler by assigning an event property: [[http://localhost:4567/eg-259/examples/lecture9/radio_click2.html|radio_click2.html]] - [[http://jsfiddle.net/cpjobling/bCNHk/1/|jsFiddle]].
----
* Code - document:
Illustrate messages for radio buttons
Illustrate messages for radio buttons
Cessna single-engine airplane descriptions
Code: JavaScript
var planeChoice = function() {
// Put the DOM address of the elements array in a local variable
var dom = document.getElementById("myForm");
// Determine which button was pressed
for (var index = 0; index < dom.planeButton.length; index++) {
if (dom.planeButton[index].checked) {
plane = dom.planeButton[index].value;
break;
}
}
// Produce an alert message about the chosen airplane
switch (plane) {
case "152":
alert("A small two-place airplane for flight training");
break;
case "172":
alert("The smaller of two four-place airplanes");
break;
case "182":
alert("The larger of two four-place airplanes");
break;
case "210":
alert("A six-place high-performance airplane");
break;
default:
alert("Error in JavaScript function planeChoice");
break;
}
};
// Register event handlers
var dom = document.getElementById("myForm")
for (index = 0; index < dom.planeButton.length; index++) {
dom.planeButton[index].onclick = planeChoice;
}
* Result:
{{eg-259:l9radio_click2.png|Radio click 2}}
===== Handling Events from Button Elements (concluded) =====
* The disadvantage of specifying handlers by assigning them to event properties is that there is no way to use parameters
* The advantages of specifying handlers by assigning them to event properties are:
- It is good to keep HTML and JavaScript separate
- The handler can be changed during use
===== Handling Events from Textbox and Password Elements =====
* The Focus Event
* Can be used to detect illicit changes to a text box by blurring the element every time the element acquires focus
* Example: [[http://localhost:4567/eg-259/examples/lecture9/nochange.html|nochange.html]] and as a [[http://jsfiddle.net/cpjobling/yEGdw/3/|jsFiddle]].
----
* Explanation: The form presents an order for coffee. when the submit button is pressed the coffee price is recomputed. A blur is added to the totals box to prevent the user being able to adjust the total.
* Code HTML:
Accessing Radio Buttons
The Focus Event
Coffee Order Form
Code: JavaScript
// The event handler function to compute the cost
var computeCost = function() {
var french = document.getElementById("french").value;
var hazlenut = document.getElementById("hazlenut").value;
var columbian = document.getElementById("columbian").value;
// Compute the cost
document.getElementById("cost").value = totalCost = french * 3.49 + hazlenut * 3.95 + columbian * 4.59;
};
document.getElementById("total_cost").onclick = computeCost;
* Result:
{{eg-259:l9-nochange.png|The form in action}}
===== Checking Form Input =====
* A good use of JavaScript, because it finds errors in form input before it is sent to the server for processing
* So, it saves both:
* Server time, and
* Internet time
===== Checking Form Input: approach =====
* Things that must be done:
- Detect the error and produce an alert message
- Put the element in focus (the ''focus'' function)
- Select the element (the ''select'' function)
----
document.getElementById("phone").focus();
* The ''select'' function highlights the text in the element
Illustrate password checking
Illustrate password checking
Choose a Password
* Code JavaScript:
// The event handler for password checking
var chkPasswords = function () {
var password = document.getElementById("password");
var confirmation = document.getElementById("password_confirmation");
if (password.value === "") {
alert("You did not enter a password \n" + "Please enter one now");
password.focus();
return false;
}
if (password.value !== confirmation.value) {
alert("The two passwords you enterd are not the same \n" + "Please re-enter both now");
password.focus();
password.select();
return false;
} else {
return true;
}
};
// Set submit button onsubmit property to the event handler
document.getElementById("password_confirmation").onblur = chkPasswords;
document.getElementById("myForm").onsubmit = chkPasswords;
* Result:
{{eg-259:l9-pswd_check.png|Password Check}}
===== Another Example =====
* Checking the format of a name and phone number
* The event handler will be triggered by the change event of the text boxes for
* If an error is found in either, an alert message is produced and both focus and select are called on the text box element
* Here is the result: [[http://localhost:4567/eg-259/examples/lecture9/validator.html|validator.html]]
----
* Code HTML:
Illustrate form input validation
Illustrate form input validation
Customer Information
* Code JavsScript:
// The event handler function for the name text box
var chkName = function() {
var myName = document.getElementById("custName");
// Test the format of the input name
// Allow the spaces after the commas to be optional
// Allow the period after the initial to be optional
var pos = myName.value.search(/^[A-Z][a-z]+, ?[A-Z][a-z]+, ?[A-Z]\.?$/);
if (pos != 0) {
alert("The name you entered (" + myName.value + ") is not in the correct form. \n" +
"The correct form is: " + "Last name, First name, Middle initial \n" +
"Please go back and fix your name");
myName.focus();
myName.select();
return false;
} else
return true;
};
// The event handler function for the phone number text box
var chkPhone = function() {
var myPhone = document.getElementById("phone");
// Test the format of the input phone number
var pos = myPhone.value.search(/^\d{3}-\d{3}-\d{4}$/);
if (pos != 0) {
alert("The phone number you entered (" + myPhone.value + ") is not in the correct form. \n" +
"The correct form is: ddd-ddd-dddd \n" +
"Please go back and fix your phone number");
myPhone.focus();
myPhone.select();
return false;
} else
return true;
};
var validate_form = function() {
return (chkName() && chkPhone());
};
// Set form element object properties to their
// corresponding event handler functions
document.getElementById("custName").onchange = chkName;
document.getElementById("phone").onchange = chkPhone;
document.getElementById("submit").onclick = validate_form;
* Result:
{{eg-259:l9-validator.png|Validator in Action}}
===== The DOM 2 Event Model =====
* Does not include DOM 0 features, but they are still supported by browsers
* DOM 2 is modularized -- one module is //Events//, which has two submodules, //HTMLEvents// and //MouseEvents//, whose interfaces are //Event// (''blur'', ''change'', etc.) and //MouseEvent// (''click'', ''mouseup'', etc.)
===== DOM 2 Event propagation =====
* The node of the document tree where the event is created is called the //target node//
* There are three phases
- The //capturing phase//
- The //second phase//
- The //bubbling phase//
===== The capturing phase =====
* Events begin at the root and move toward the target node
* Registered and enabled event handlers at nodes along the way are run
===== The second phase =====
* The second phase is at the target node
* If there are registered handlers there for the event, they are run
===== The bubbling phase =====
* Event goes back to the root; all encountered registered handlers are run
===== The DOM 2 Event Model (continued) =====
* Not all events bubble (e.g., ''load'' and ''unload'')
* Any handler can stop further event propagation by calling the ''stopPropagation'' method of the ''Event'' object
* DOM 2 model uses the ''Event'' object method, ''preventDefault'', to stop default operations, such as submission of a form, if an error has been detected
===== Registering event handlers =====
* Event handler registration is done with the ''addEventListener'' method
* Three parameters:
* Name of the event, as a string literal
* The handler function
* A Boolean value that specifies whether the event is enabled during the capturing phase:
node.addEventListener("change", chkName, false);
----
// validator2.js
// An example of input validation using the change and submit
// events, using the DOM 2 event model
// Note: This document does not work with IE6
var chkName = function(event) {
// Get the target node of the event
var myName = event.currentTarget;
// Test the format of the input name
// Allow the spaces after the commas to be optional
// Allow the period after the initial to be optional
var pos = myName.value.search(/^[A-Z][a-z]+, ?[A-Z][a-z]+, ?[A-Z]\.?$/);
if (pos != 0) {
alert("The name you entered (" + myName.value + ") is not in the correct form. \n" +
"The correct form is: " + "Last name, First name, Middle initial \n" +
"Please go back and fix your name");
myName.focus();
myName.select();
}
};
// The event handler function for the phone number text box
var chkPhone = function(event) {
var myPhone = event.currentTarget;
// Test the format of the input phone number
var pos = myPhone.value.search(/^\d{3}-\d{3}-\d{4}$/);
if (pos != 0) {
alert("The phone number you entered (" + myPhone.value + ") is not in the correct form. \n" +
"The correct form is: ddd-ddd-dddd \n" +
"Please go back and fix your phone number");
myPhone.focus();
myPhone.select();
}
};
// Set form element object properties to their
// corresponding event handler functions
// Get the DOM addresses of the elements and register
// the event handlers
var customerNode = document.getElementById("custName");
var phoneNode = document.getElementById("phone");
customerNode.addEventListener("change", chkName, false);
phoneNode.addEventListener("change", chkPhone, false);
// Challenge ... how would you check both name and telephone number on submit?
Using navigator
===== Summary of This Lecture =====
More on the event model, using events for form validation, and the DOM 2 event model.
* [[eg-259:lecture9#handling_events_from_button_elements_more|Handling Events from Button Elements (more)]]
* [[eg-259:lecture9#handling_events_from_textbox_and_password_elements|Handling Events from Textbox and Password Elements]]
* [[eg-259:lecture9#the_dom_2_event_model|The DOM 2 Event Model]]
* [[eg-259:lecture9#the_navigator_object|The Navigator Object]]
===== Learning Outcomes =====
//At the end of this lecture you should be able to answer these questions//:
* What is the disadvantage of assigning event handlers to event properties?
* What are the advantages of assigning event handlers to event properties?
* Why is it good to use JavaScript to check the validity of form inputs before the form data is sent to the server?
* What three things should be done when a form input element is found to have incorrectly formatted data?
* What happens when an event handler for the ''onsubmit'' event returns ''false''?
===== Learning Outcomes (continued) =====
//At the end of this lecture you should be able to answer these questions//:
* What event is used to trigger an event handler that checks the validity of input for a text button in a form?
* Explain the three phases of event processing in the DOM 2 event model.
* Give two examples of default actions of events.
* Explain the first two parameters of the ''addEventListener'' method.
===== Learning Outcomes (continued) =====
//At the end of this lecture you should be able to answer these questions//:
* How is an event handler registered so that it will he called during the capturing phase?
* How can an event handler be unregistered?
* What exactly do the ''clientX'' and ''clientY'' properties store?
* What purpose does the //navigator// object have?
There are some more review questions [[eg-259:review:js_html2|available]].
===== Further Exercises 1 =====
- Rewrite the document for the exercises of the [[eg-259:lecture8#homework_exercises|previous lecture]] to use the DOM 2 event model.
- Develop, test, and validate an HTML document that has check boxes for apple (59p each), orange (49p each), and banana (39p each), along with a submit button. Each of the check boxes should have its own ''onclick'' event handler. These handlers must add the cost of their fruit to the total cost. An event handler for the //Submit// button must produce an alert window with the message ''%%"%%Your total cost is //xxx// p,%%"%%'' where //xxx// is the total cost of the chosen fruit plus 17.5 percent VAT. This handler must return ''false'' (to avoid actual submission of the form data).
===== Further Exercises 2 =====
- Develop, test, and validate an HTML document that is similar to that of Further Exercises 1.2. In this case, use text boxes rather than check boxes. These text boxes take a number, which is the purchased number of the particular fruit. The rest of the document should behave exactly like that of Exercise 1.2.
- Add reality checks to the text boxes of the document in Further Exercises 2.1. The checks on the check box inputs should ensure that the input values are numbers in the range 0-99.
- Revise the document of Further Exercises 2.1 to use the DOM 2 event model.
===== What's Next? =====
JavaScript libraries
* [[eg-259:ch14#General_Purpose_JavaScript_Libraries|General Purpose JavaScript Libraries]]
* [[eg-259:ch14#Special_Purpose_JavaScript_Libraries|Specialized JavaScript Libraries]]
* [[eg-259:ch14#Using_Libraries|Using Libraries]]
* [[eg-259:ch14#jQuery|jQuery]]
* [[eg-259:ch14#Example|Example]]
* [[eg-259:ch14#jQuery_UI Components|jQuery UI Components]]
* [[eg-259:ch14#Using_CDN|Using CDN]]
[[eg-259:lecture8|Previous Lecture]] | [[eg-259:home]] | [[eg-259:ch14|Next Lecture]]