HOME  |    TRAINING  |   FREE TUTORIALS
Find out more about our new RSS feed.
FREE Tutorial
BEGINNING JAVASCRIPT PART 1 - HTML

CATEGORY
SEARCH OUR OTHER TUTORIALS

DESCRIPTION

Web pages would be very boring if we could not interact with the user, or obtain information from them, such as text, numbers, or dates. Luckily, with JavaScript we can. We can use this information within the web page, or it can be posted to the web server where we can manipulate it and store it in a database if we so wish.


This free tutorial is a sample from the book Beginning JavaScript.


When using your computer you'll be quite accustomed to various user interface elements. For example, the Windows operating system has a number of standard elements such as buttons you can click, lists, drop down list boxes, and radio buttons you can select from, and checkboxes you can tick. The same applies with any Graphical User Interface (GUI) operating system, whether it's on the Apple Mac, Unix, or Linux. These elements are the way we now interface with applications. The good news is that we can include many of these types of element in our web page and, even better, it's very easy to do so. Once we have such an element, say a button, inside our page we can then tie code to its events. For example, when the button is clicked, we can fire off a JavaScript function we've created.

It's important to note at this point that the elements I'm talking about in this chapter are the common elements made available by HTML, and not ActiveX elements, Java Applets or plug-ins.

All of the HTML elements used for interaction must be placed inside an HTML form. Let's start by taking a look at HTML forms and how we interact with them in JavaScript.

HTML Forms

Forms provide us with a way of grouping HTML interaction elements with a common purpose together. For example, a form may contain elements that enable the input of a user's data for registering on a web site. Another form may contain elements that enable the user to ask for a car insurance quote. It's possible to have a number of separate forms in a single page. Pages containing multiple forms need not worry us until we are submitting information to a web server - then we need to be aware that only the information from one of the forms on a page can be submitted to the server at once.

To create a form, we use the <FORM> and </FORM> tags to declare where it starts and where it ends. The

tag has a number of attributes, such as the ACTION attribute, which determines where the form is submitted to, the METHOD attribute, which determines how the information is submitted, and the TARGET attribute, which determines the frame to which the response to the form is loaded.

Generally speaking, for client-side scripting where we have no intention of submitting information to a server, these attributes are not necessary. When in a later chapter we look at programming server pages, then these properties will come into play. For now the only attribute we need to set in the tag is the NAME attribute, so that we can reference the form.

So, to create a blank form, the tags required would look something like:
<FORM NAME="myForm">
</FORM>

You won't be surprised to hear that these tags create a Form object, which we can use to access the form. We access this object in two ways.

Firstly, we can access the object directly using its name, here document.myForm.

Alternatively we can access the object through the document object's forms[] array property. Remember in the last chapter we talked about the document object's images[] array, and how we could manipulate it like any other array. Exactly the same applies to the forms[] array, except that instead of each element in the array holding an IMG object, it now hold a Form object. For example, if our Form was the first Form in the page, we would reference it using document.forms[0].

Many of the attributes of the tag can be accessed as properties of the Form object. In particular, the name property of the Form object mirrors the NAME attribute of the tag.

Try It Out - The forms Array

Let's have a look at an example that uses the forms array. Here we have a page with three forms on it. Using the forms[] array we access each Form object in turn and show the value of its name property in a message box.

<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript>

function window_onload()
{
  var numberForms = document.forms.length;
  var formIndex;
  for (formIndex = 0; formIndex < numberForms; formIndex++)
  {
   alert(document.forms[formIndex].name);
  }
}

</SCRIPT>
</HEAD>
<BODY LANGUAGE=JavaScript onload="window_onload()">

<FORM NAME="form1">
<P>This is inside form1</P>
</FORM>

<FORM NAME="form2">
<P>This is inside form2

</FORM> <FORM NAME="form3"> <P>This is inside form3

</FORM> </BODY> </HTML>

Save this as ch6_examp1.htm. When you load it into your browser, you should see three alert boxes, each of which shows a name of a form.

How It Works

Within the body of the page we define three forms. Each form is given a name, and contains a paragraph of text.

Within the definition of the tag, the window_onload() function is connected to the window object's onload event handler.

<BODY LANGUAGE=JavaScript onload="return window_onload()">

This means that when the page is loaded, our window_onload() function will be called.

The window_onload() function is defined in a script block in the head of the page. Within this function we loop through the forms[] array. Just like any other JavaScript array, the forms[] array has a length property, which we can use to determine how many times we need to loop. Actually, as we know how many forms there are, we could just write the number in. However, here I'm demonstrating the length property, since it is then easier to add to the array without having to change the function. Generalizing your code like this is a good practice to get into.

The function starts by getting the number of Form objects within the forms array and stores it in variable numberForms.

function window_onload()
{
  var numberForms = document.forms.length;

Next we define a variable, formIndex, to be used in our for loop. After this comes the for loop itself.

var formIndex;
for (formIndex = 0; formIndex < numberForms; formIndex++)
{
  alert(document.forms[formIndex].name);
}

Remember that since the indices for arrays start at zero, our loop needs to go from an index of 0 to an index of numberForms - 1. We do this by initializing the formIndex variable to zero, and setting the condition of the for loop to formIndex < numberForms.

Within the for loop's code, we pass the index of the form we want (that is, formIndex) to document.forms[], which gives us the Form object at that array index in the forms array. To access the Form object's name property, we put a dot at the end and the name of the property, name.

Other Form Object Properties and Methods

The HTML elements commonly found in forms, which we will look at in more detail shortly, also have corresponding objects. One way of accessing these is through the elements[] property of the Form object. This is an array just like the forms[] array property of the document object that we have just seen. The elements[] array contains all the objects corresponding to the HTML interaction elements within the form, with the exception of the little used <INPUT TYPE=image> element. As we'll see later, this property is very useful for looping through each of the elements in a form. For example, we could loop through each element checking that it contains valid data prior to submitting the form.

Being an array, the elements[] property of the Form object has the length property, which tells us how many elements are in the form. The Form object also has the length property, which also gives us the number of elements in the form. Which of these you use is up to you since both do the same job, although writing document.myForm.length is shorter, and so quicker to type and less lengthy to look at in code, than document.myForm.elements.length.

When we submit data from a form to a server, we normally use the submit button, which we will come to shortly. However, the Form object also has the submit() method which does nearly the same thing. It differs in Netscape Navigator since it does not call the onsubmit event handler for the submit event of the Form object.

Recall that in the last chapter we saw how return values passed back from an event handler's code can affect whether the normal course of events continues or is cancelled. We saw, for example, that returning false from a hyperlink's onclick event handler causes the link's navigation to be cancelled. Well, the same principle applies to the Form object's onsubmit event handler, which fires when the user submits the form. If we return true to this event handler, then the form submission goes ahead; if we return false then the submission is cancelled. This makes the onsubmit event handler's code a great place to do form validation; checking that what the user has entered into the form is valid. For example, if we ask for their age and they enter "mind your own business" we can spot that this is text rather than a valid number, and stop them from continuing.

As well as there being a reset button the Form object has the reset() method, which clears the form, or restores default values if these exist. Creating blank forms is not exactly exciting or useful.




5 RELATED COURSES AVAILABLE
JAVASCRIPT PROGRAMMING
This training course aims to teach the reader the fundamentals of JavaScript. This course covers topics such as -....
HTML 4.0 INTRODUCTION
To create, format and publish a small website using HTML 4.0. You will learn to create web pages incorporating fo....
INTRODUCTION TO JAVA PROGRAMMING
The aims of this Java training courses is to understand the role that Java plays on the Internet; describe the be....
MICROSOFT VISUAL BASIC V6 INTRODUCTION
To go from the fundamentals of Visual Basic programming to the threshold of Advanced level. Gaining in depth prog....
MICROSOFT VISUAL BASIC 5.0 CLIENT SERVER DEVELOPMENT
This course teaches the skills required to develop client server applications using MS Visual Basic 5.0 Enterpris....
CONTACT US
Friday 19th March 2010  © COPYRIGHT 2010 - VISUALSOFT