Examples


This section contains examples of forms and JavaScript. The projects explained here include handling form input, changing an image when the mouse moves over it and a slide show. The CD-ROM contains the code for the projects in the folder named chapter3code.

Forms

On the CD The handling of form input by server-side scripts using PHP and ASP is the focus of much of this book. However, to start the explanation of forms, we begin with what could be dismissed as a “write-only” program. It accepts data, but does not do anything with it except demonstrate how forms are displayed.

    <html>     <head><title>Form data </title>     </head>     <body>     <h1>Student Information </h1>     <hr>     <form action="test.html" method="get">     First Name <input type=text name='fname'>     Last Name <input type=text name='lname'><br>     Choose one <input type='radio' name='category'      value='newmedia'> New Media     <input type='radio' name='category' value='math'>     Math/Computer science     <input type='radio' name='category' value='LAS'>     Other LAS       <input type='radio' name='category'      value='arts'> Conservatories     <input type='radio' name='category' value='CE'>      Continuing education      <br><input type=submit value="SEND">     </form>     <body>     </html>

The <hr> tag (hr stands for horizontal rule) creates the line across the screen.

Create this in your text editor and save it as test.html. When you open it in a browser, it should look like Figure 3.1.

click to expand
Figure 3.1: Sample form.

You can fill out the form. Notice how you can only choose one of the “Choose one” categories. This is because they are specified as radio inputs with the same name. Click on the SEND button. You will see something like what appears in the location field in Figure 3.2.

click to expand
Figure 3.2: Entity relationship diagram.

We say “something like” because presumably you used another name. The text starting with test.html shows how the browser handles form submission. The form input field names and the values typed in are added to the name of the file specified by the action attribute. This is called the query string and is made up of the filename, followed by a question mark, and then field name and values separated by equal signs and strung together using ampersands. We have made the action file the same as the file holding the form just to make it a file that we know exists. In later chapters in this text, you will see some examples in which one file both presents the form and handles the form input, and other cases in which a different file is specified to handle the form.

The next example is more complex, but actually does something! The client-side script takes the input, performs calculations, and displays the results on the page. The following notes provide an outline for the coding. You will find it useful to prepare similar notes for your own work.

Head section containing a definition for a function named addup.

The function addup extracts the form data, does a calculation, and then does a further calculation to make sure the answer is formatted as dollars and cents. The result is displayed back in the form.

Body section containing a form. The form is used for input and output.

This example uses a plan for pricing that might or might not be what is done at the coffee shop you visit. There are three types of drinks. A base price is associated with each type and a size factor with each size. The cost of a drink is the base price times the size factor. This coffee shop also applies a tax rate of a fixed 8%.

Table 3.2 shows the code in the first column and an explanation in the second. Keep in mind that explaining code or script often poses “chicken and the egg” type problems. Be patient with the book and with yourself.

Table 3.2: HTML/JavaScript Calculation Example

<html><head><title> Calculation</title>

Normal HTML.

<script language="JavaScript">

Sets off the script. Indicates the language. An alternative is VBScript

function addup(f) {

A function definition. The mate of the curly bracket is below at #. The argument has the name f. It will be the name of the form

var total; var taxrate = .08 ; var drinkbase; var opts;

Declaration of variables. The value of tax rate is set to .08

opts=f.drink;

This will be the set of options within the drink tag

drinkbase = f.drink[opts.selectedIndex] .value;

The opts.selectedIndex will hold the number (position) of whatever the person filling out the form has selected. Using this value as an index (square brackets) to f.drink indicates the option. Using “dot value” then extracts the value

var sizefactor; var i; var totals; var dp;

More declarations

for (i=0;i<f.sizef.length;i++) {

for statement to go through all the possibilities for sizes

if (f.sizef[i].checked) {

Check if this was the size checked

sizefactor = f.sizef[i].value;

If so, set sizefactor equal to the corresponding value

} }

Ends the if. Ends the for loop

total = sizefactor * drinkbase;

Multiply the sizefactor by the drinkbase

total = total*(1 + taxrate);

Add in taxes

f.label.value="Total with tax";

Output a description of what the answer is

f.totalf.value=total;

Output the total (but this could change)

totals = f.totalf.value + "00";

Make sure it is dollars and cents by adding the string “00”

dp = totals.indexOf(".");

Determine if there was a decimal point

if (dp<0) {

If there wasn’t a decimal point, the indexOf method for strings will return –1 if it couldn’t find a decimal point

f.totalf.value = "$" + f.totalf.value+".00";

Format the output value with a dollar sign and trailing zeros, and place in the totalf position in the form

return false;

This return false stops the browser from taking the action for the form

}

Ends the if clause

else {

Otherwise (if the condition isn’t true), do the else clause

totals = "$" + totals.substr(0,dp+3);

Add the number of zeros that you need

f.totalf.value = totals;

Put in the totalf position

return false;

Return false as before

}

Ends the else clause

}

Ends the function definition

</script></head>

Ends the script tag and the head tag

<body><h2> Coffee shop </h2><p>

Normal HTML

<form name="orderf" onsubmit="return addup(this);">

Form tag. Indicates a name. Indicates that when the submit event happens, call the addup function using this form as the argument. Return whatever it returns

<select name="drink">

Select tag. It has the name “drink”

<option value="2.50">Coffee

The options will be the base prices for the three options for drinks

<option value="2.25">Hot Cocoa

See above

<option value="1.00">Chai

See above

</select><br>

End the select. HTML line break

<input type="radio" name="sizef" value="1">Tall

First of three radio input tags. Grouped by the common name. The value is the size factor

<input type="radio" name="sizef" value="1.5">Grand

Second of this group of radio buttons

<input type="radio" name="sizef" value="2"> Super

Third of this group of radio buttons

<input type=submit value="Order"><br>

Forms the submit button. The label is “Order”

<br><input type="text" name="label" value="">

The is an input tag, but it will be used to show the customer something, namely the phrase “Total with Tax”

<input type=text name="totalf" value="">

Another input tag used for output. It will have the calculated, formatted total

</form></body></html>

HTML closing tags

The DOM is in heavy use in this example, defining how to read from and write to the form. The select and option tags, which implement the menu, require you (your code) to get the index of what was selected and then use that number to get the actual value.

    f.drink[opts.selectedIndex].value 

You interpret this by reading from the inside out: the opts is the name of the select tag. The programmer of this example chose that name; there is nothing special about it. The property selectedIndex is from the DOM. This returns the index (you can think of it as a position). A selection of coffee would yield a zero; hot cocoa, a one; and chai, a two. Indexing starts from zero, and not one, in JavaScript. Coding f.drink (the drink tag in the form f) followed by square brackets containing a number, will produce that option tag. The last operation is to extract the value attribute of that option tag. All the option tag values, as indicated previously, have been set to be used directly in the calculation.

This HTML file produces the screen shown in Figure 3.3.

click to expand
Figure 3.3: Form to be filled out.

Once you have this (or something like it—do put in different names for the drinks and the sizes to test and strengthen your understanding), select a drink from the pull-down menu, click on a size, and then click on the Order button. Notice that filling out this form does assume that the customer is familiar with filling out these types of forms. What do you see? Figure 3.4 shows a possible result.

click to expand
Figure 3.4: Filled-out form.

Client-Side Debugging

To prepare you for debugging your own scripts, what if you made the mistake of writing the for statement as:

    for (i=0;i<=f.sizef.length;i++) { 

This is understandable: the reason it is wrong is because the indexing of arrays starts with zero and ends with one less than the length of the array. The effect of this mistake is that nothing happens, except clearing the form. The dot disappears from whichever radio button you selected. The browser “knows” that there is a problem, but does not tell you what it is. You need to examine your code. In Netscape, you have a feature that might help. You can type:

    javascript:

in the location field where you generally type in a URL. Netscape will display a JavaScript Console window (see Figure 3.5).

click to expand
Figure 3.5: Error message in JavaScript console. Web browser 2003 Netscape.

Internet Explorer does not have this feature.

If you count the line numbers in the html source, you will see f.size[i]. The message is telling you that f.sizef[i] does not exist. This is a hint—it certainly is not a direct message—that you need to check out the value of the variable i. Hopefully, this will cause you to examine the for statement and realize that the limiting condition on the loop was an error. Alternatively, you could insert a statement such as:

    alert("The value of i is: "+i);

right after the opening curly bracket. In this situation, you will see screens resembling Figure 3.6 when the browser displays an alert window for i equal to zero, 1, 2, and 3. You will need to click OK to continue each time.

click to expand
Figure 3.6: Display of HTML with Alert box.

When you see the 3, you need to figure out that this was the problem: the variable i should not have been greater than 2. Alert statements are one of the few tools you have for debugging HTML and JavaScript.

The system detected a problem situation at one place; the problem actually occurred at another place. You will need to cope with such situations.

The previous example demonstrated one type of bug. It was troublesome because the system did not indicate much more than that there was a problem. What if you made a mistake in the values you inserted for the tax rate or the prices of the types of drinks? The answer is that this might be a problem for the coffee shop and the customers, but it is not a problem to the browser. This is sometimes referred to as a logical bug and not a syntactic or programming problem. You need to detect and find these by yourself. One approach is to prepare what is elegantly called a test suite of input conditions, with the corresponding correct output recorded to be compared with what the system produces. It is also a good tactic to have someone else help debug your work.

Mouse Rollover to Swap Images

The next example might be the most frequently used JavaScript application: swapping images when the mouse goes over and out from the image. The coding makes use of a JavaScript function defined in the head section and small pieces of JavaScript in the <a> tags. The example also shows event handling. The event in the previous example was the submission of a form. The events here relate to the mouse. The outline for the script is as follows:

Head section containing definition of a function called movein. Its argument will be the name of the image to be moved into a set image tag. This means that the same function can be used for moving in either image.

Body section containing an a tag. The attributes of the <a> tag specify event handling. The content of the a tag is an image tag. The image tag has a name.

Here is the code shown and explained in Table 3.3.

Table 3.3: HTML/JavaScript for Mouse Rollover Image Swap

<html>

HTML tag

<head>

Head tag

<title> Rollover test </title>

Title tag

<script language="JavaScript">

Starting script tag

<!—

Comment (used to shield the code from older browsers)

function movein(image)

Start of function named movein. Its argument will be the name of an image file

{

Start of function body

window.document.picture1.src=image;

Make picture1 display image

}

End of function body

// End —>

Ending comments

</script>

Closing script tag

</head>

Closing head

<body>

Start of body

This is the start of the page.

Normal text

<a href=""

Start of an a tag. The href attribute is empty

onMouseOver="movein(frog.gif');"

Specifies the handling of the mouse over event to be calling the function movein with argument the frog file

onClick="return false;"

Specifies the handling of the click event to be return false. This means that the browser won’t do anything. (Otherwise, it would refresh the screen and restore the original image)

onMouseOut="movein('bird.gif');"

Specifies the handling of the mouse out event—moving the cursor out from the a tag—to be calling the function movein with argument the bird file

>

Ends the a (starting a) tag

<img src="/books/2/886/1/html/2/bird.gif" name="picture1" height="100" >

The contents of the a tag, what is between the a tag and the /a tag, is an image tag. It has a name attribute of “picture1.” It also has src and height attributes

</a>

The /a tag

</body>

End of body

</html>

End of HTML

This example follows the practice of using comments to set off the contents of the script tags. This is less necessary then it once was, because most browsers now recognize the <script> tags.

To implement this example, you need two image files. Figure 3.7 shows what the book example looks like when first opened in the browser.

click to expand
Figure 3.7: Initial display showing first image.

When a visitor moves the mouse over the image of the bird, the screen becomes what is shown in Figure 3.8.

click to expand
Figure 3.8: Display of second image.

Slide Show

The last JavaScript example is a slide show. The project makes use of JavaScript functions that set up timed events, setInterval and clearInterval. The example also uses an array. An array is a list of items; in this case, a list of names of image files. Actually, you were introduced to arrays in the coffee shop example. The select element held an array of options. Arrays have their own set of properties. One property used here is the length of the array. Particular elements of an array are referenced using square brackets. The outline for this project is shown followed by Table 3.5 showing the HTML and JavaScript.

Head section containing

An array of filenames

Definition of the change function, for changing the image

Definition of the startss function that starts the timing event process that implements the slide show

Definition of the stopss function that stops the timing event

Body section containing

An a tag, contents, and closing a tag that implements the button to start the slideshow

An a tag, contents, and closing a tag, that implements the button to stop the slideshow

An image tag, distinct from anything else

Table 3.5: HTML/JavaScript for Slide Show

<html>

Start html

<head><title>Slide show </title>

Head and title

<script LANGUAGE="JavaScript">

Script tag

<!—

Comment to set off script

slides = new Array(

Defines slides as an array, using the term “new.” The array contains three elements:

'bird.gif',

A string holding the name of an image

'frog.gif',

Another image filename

'heart.gif'

Another image filename

);

Closes the array definition

var sn = 0;

A variable declaration and initialization

var ns = slides.length;

A variable declaration and initialization: ns will hold the number of items in the array

var tid;

A variable to hold the timing event number

function change() {

Start of the definition of the change function. It has no arguments

document.pic1.src = slides[sn];

The value of sn is assumed to hold the number for the next image. The slides array holds the names of all the image files. The sn one is now made the value of the src attribute. This effectively changes the image shown

if (ns<= ++sn) {

The variable sn is incremented (by the ++ operator before the variable). This is done compared to ns. If the new value of sn turns out to be greater than or equal to ns, then the if clause is executed

sn = 0;

sn is put back to zero

}

Close the if clause

}

Close the function

function startss() {

Start of startss function definition. It has no arguments

tid=setInterval('change()',800);

The timing event is established. The function change() will be called every 800 milliseconds. The number identifying this event is stored in the variable tid

}

End the startss function

function stopss() {

Start of stopss function. No arguments

window.clearInterval(tid);

Stop the timing event, using tid

}

End the function

//—></script>

End the comment and the script

</head>

End the head section

<body>

Start the body section

<br>

Line break

<a href="javascript:startss()">

The a tag has as the value of the attribute href some JavaScript code. The code is startss(). This means that when the viewer clicks this hyperlink, this code gets invoked

Start show </a>&nbsp; &nbsp;

The contents of the hyperlink (the words Start show, the /a tag and then two spaces. This special coding for blanks is required to space out the two hyperlinks

<a href="javascript:stopss()">Stop Show </a><br>

Another a tag, contents and closing a tag. The href in the a tag indicates a call to stopss()

<img src='/books/2/886/1/html/2/bird.gif' name='pic1' id='pic1'>

An image tag. Notice that it has a name and an id

</body>

End body

</html>

End html

Figure 3.9 shows the starting display for this example.

click to expand
Figure 3.9: Starting display of HTML slide show.

Figure 3.10 shows a display after the slide show has been stopped, with a different image.

click to expand
Figure 3.10: Display of slide show with a different image.

The event that occurs every 800 milliseconds is handled by calling the change function. Its tasks are to increment the variable sn (done using the ++ prefix operator) and then use sn to move to the next image. The critical part of the incrementing is to know when to start over. Recall that the indexing starts at zero. This means that the last element has index one less than the number of elements in the array. The ns variable in the example here will have the value 3. Therefore, when sn gets bumped up to 3, the code resets it to zero. The constant 3 does not occur in the code. The length property of the array named slides returns the correct value.

Make a slide show with four images. All you need to do is squeeze in a line before the parentheses ending the array definition.

Preventing Errors

When writing HTML and JavaScript applications such as these, it is good practice to review your work by doing the following:

  • Check that opening tags are matched with closing tags.

  • Check that opening braces (curly brackets) are matched with closing braces, opening pointy brackets are matched with closing pointy brackets, and opening parentheses with closing parentheses.

  • Check that you have quotation marks around attribute values and character strings, and make sure you have not omitted the closing quotation marks. Use single quotes within larger strings delimited by double quotes.

  • Check that spelling agrees between the setting of a variable and its name in an expression, or the definition of a form input element and its use in JavaScript.

  • Check references to filenames for spelling. This is more difficult than the prior check because it involves something outside the HTML file.

  • Check the starting and stopping values in any looping (e.g., for statement).

Errors will still occur, but these are the most common sources of problems. A general strategy is to proceed slowly. Try to build on what you know by taking a script that works and making changes to it to turn it into a script that does a new task. Test the changes one at a time.




Creating Database Web Applications with PHP and ASP
Creating Database Web Applications with PHP and ASP (Charles River Media Internet & Web Design)
ISBN: 1584502649
EAN: 2147483647
Year: 2005
Pages: 125
Authors: Jeanine Meyer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net