BIT 116 – Scripting
Exercise 8

Event handling


Part 1: Defining the onClick Event Handler for a Button

In the body of a web page, define a form, and on the form define a button. Define the body of the onClick event handler for the button so that an alert message is displayed when the button is clicked.

Remember that to define an event handler, you assign a string containing the JavaScript statements that comprise the body of the handler, separated by semicolons, to the name of the event inside the html tag.

Part 2: Using the Value of a Text Box in an Event Handler

In the body of a web page, define a form, and on the form define both a text box and a button. Provide a name attribute for the text box so that it's value field can be easily retrieved. Define the onClick event handler for the button so that it alerts the user with the text that is visible in the text box using the value field of the text box.

Part 3: Calling Your Own Function from an Event Handler

Define a function in the head section of a web page that accepts a single String as a parameter and alerts the user using the parameter's value.

Use the form from Part II in the body of the page, except alter the onClick event handler to call your function, using the value field of the text box as its only argument.

Part 4: Generating a Button for Each Element of an Array

Declare an array and assign some strings to it - 4 to 8 strings will do.

Use a for loop to write out the html for a button for each element in the array. In the onClick event handler for each button, pop up an alert box that displays the string stored in the corresponding array element. The captions (defined using the value attribute) of the buttons can just be "Button 1", "Button 2", etc.

This exercise requires you to write JavaScript statements (the onClick event handlers) from JavaScript statements (the for loop). This is a tricky concept. Remember to enclose the JavaScript statements inside the event handlers inside a different style of quotation mark than you use to enclose the string that you are writing to the document.

Part 5: Good and Evil and Event Handlers

Do the exercise behind the link labeled "Event Handlers: For Good and For Ill", on the main page.

Part 6: The Document object

Do the exercise behind the link labeled "The Document Object", on the main page.