Introduction To Javascript
Using Forms


Forms are a part of HTML designed to allow user input. Javascript can access the different elements of the form (text boxes etc.), find out their status or value and even change the values.

Setting up a form

The first stage of a form is the <form> tag itself. There must be a <form> tag before the elements of the form in the HTML and a </form> tag at the end. The following example uses a text boxes and buttons to create a form.

<form name="myForm">
What is your name?<BR>
<input type="text" name="myName"> <BR>
<button type="reset">Reset</button>
<button onclick="myFunction()"> Press Me! </button>

The following function is in the head of the document.

function myFunction() {
var person = document.myForm.myName.value
document.write("Your name is " + person)

This code produces a text box and 2 buttons. The reset button clears any text entered into the text box. The second button calls the function when clicked. (Onclick is an event handler used to call a function when the specified element is clicked). The name of the person is then written to the screen. Because the page has already loaded this information is outputted to a new page.

The value that has been entered into the text box is copied to the variable person with the statement var person = document.myForm.myName.value. Each different form element should have a unique name to allow its contents to be referenced and used by Javascript.

Exercise 11

Copy and use the code listed above to produce a game which writes a story based on words that the user enters into a form. Eg. User enters the name Cartman in a text box labelled Enter a name. When the story is outputted, it reads, Once upon a time there was a boy called Cartman.... Your story should include at least 5 items from the user.