Conceptual Explanation


This section includes examples of client-side JavaScript programming, including handling forms and events.

Basic Programming Constructs

As noted in Chapter 1, “Introduction,” scripts refer to files in languages that are stored more or less as you write them, and translated into action when they are used. This is in contrast to the procedure used in “full” programming languages in which source files are transformed in a process called compilation into a format for execution. Having established that, JavaScript still has many features in common with “full” programming languages, including variables, functions, expressions, statements, and event handling.

Variables are the computer science term for associating names with values. The values might vary—hence the name. The type of value might be a string of characters representing something such as a name, or a number representing the number of items someone wants to purchase.

Function is the term used in JavaScript for giving a name to a set of statements. When you use the name, the whole set of statements is executed. It is like defining a “shorthand” way of specifying a long process. The function can be used as if it were part of the basic language. Other programming languages use the term function in a more restrictive way, and the terms procedure, method, and subroutine are also commonplace. You will be using functions that are part of JavaScript, functions that are methods associated with objects (using the Document Object Model to be described), and functions you define. A function can have as part of its definition the specification of an argument or a set of arguments. These are values that will be used by the function.

Expressions are combinations of variables, operators such as +, and invocations of functions or methods. The JavaScript language is made up of a certain set of allowable statements. An example is an assignment statement, in which a variable is assigned the value of an expression.

    cost = num_of_items * price;

The asterisk (*) is the operator designating multiplication. Its use for multiplication is common to many computer languages. The plus sign (+) is for addition of numbers and also for concatenation of strings. The minus sign (–) is for subtraction, and the slash (/) is for division.

Assuming that num_of_items and price are each variables set earlier to be numeric values such as 5 and 1.25, respectively, the interpretation of this statement is: Determine the current value of num_of_items and multiply it by the current value of price. Take the result and assign it to be the current value of the variable cost. The thing doing these operations of determining values, multiplying, and assigning is the JavaScript program.

Statements are ended with semicolons. JavaScript (and other computer languages) does not use periods because periods are used as decimal points in numbers. Periods (dots) also are used to indicate the properties or the methods (procedures) associated with objects. Objects encapsulate data, formally called attributes or properties, and operations or procedures, formally called methods. The definition of ASP, which you will study in this book, consists of the definition of several objects.

Events refer to situations that the underlying system can recognize. If the person at the client computer uses the mouse to click on a button, that is an event, and you, the programmer, can specify how the event is to be handled; that is, what you want to happen. Similarly, submitting a form is an event.

Forms

The HTML discussed in this chapter is somewhat more intricate than the previous chapter. There are tags within tags. You will need to distinguish between the attributes within the pointy brackets of the tag and the HTML between the starting tag and the ending tag; for example, the <form> and the </form>.

HTML has a set of tags that provide ways to gather information. The <form> tag has attributes that specify how the form information is to be processed. Two examples of a form tag are:

    <form name="order" action="takeorder.php">     <form name="order" action=""         onSubmit="calculatebill(this);"> 

In both cases, the form is named "order". For the first example, the input from the form will be sent to a file named takeorder.php. This script is called the handler of the form. How the PHP file accesses the form data is the subject of a later chapter. In the second example, a function is called named calculatebill. The argument this has a special meaning, referring to the object, the form itself. The input of the form is not sent to another file for action as indicated by the action attribute being set to an empty string. This example will be expanded later in the book.

Form tags come in pairs. Within the <form> and </form> tags, you can place any HTML (text and/or tags) and several specific tags that specify the type of input and output. By output, we mean displaying information generated by the program for the person to see. The input tags have attributes in common, such as name, used for referring to the input contents, and value, used to specify a default value. Table 3.1 shows the basic tags for forms.

Table 3.1: Basic Tags and Attributes for HTML Forms

Example

Purpose

<input type="text" name="lname" >

Text input and output

<input type="hidden" name="pw">

Hidden: text input in which asterisks (*) hide what the person types from someone peeking at the screen

<input type="submit" value="SEND">

Submit button

<input type="reset" value="CLEAR">

Reset button

<select name="drink"><option value="coffee">Coffee<option value="cocoa">Hot Cocoa<option value="chai">Chai</select><br>i

Drop -down menu

<input type=”radio” name=”sizef” value=”sm”>Tall <input type=”radio” name=”sizef” value=”med”>Grand<input type=”radio” name=”sizef” value=”big”> Super

Radio buttons (the name attribute defines a set in which only one in the set is allowed to be selected)

Document Object Model and Client-Side Scripting

These tags will be shown in use in the Examples section. As the first step in demonstrating JavaScript, we introduce the Document Object Model (DOM). The DOM defines how any scripting language must refer to the HTML document, and is relevant to client-side scripting only. The DOM uses object syntax. The following is an example of use of the DOM:

    order.lname.value 

This could refer to the value entered by the customer to the input named lname of the form named order. Another use of the DOM is to dynamically add something to the HTML document. You will do this using the write method of the document object. A simple example of this is:

    document.write("<h1>Welcome</h1>");

In this example, document is an object, a very special one, in fact, and write is one of its methods. A method is a type of function or a procedure. The write method uses its argument, the information in the parentheses, and does something with it. This should not be confused with Response.Write, shown in Chapter 1 in an example of a server-side script using ASP with JavaScript.

A more interesting example is:

    document.write("Today is " + Date());

The proper way to describe how this statement is interpreted is to begin inside the parentheses and work out. The “Today is”is a string (character string). Notice that the very last character is a blank. The plus sign is not addition of numbers, because there are no numbers here. Instead, it is the concatenation of strings. The Date() is an invocation of a built-in JavaScript function. It has an empty argument. The Date() function returns the current date and time in a special format. However, because the context here is concatenating strings, JavaScript turns the returned Date into a string. This result is what is written out to the HTML document.

More examples of use of the DOM and other functions come later.

The previous assignment statement is one type of JavaScript statement. The use of document.write is another type, namely a function or method invocation. JavaScript also provides a way to do something only if a certain condition is true. This is known as an if statement. The if statement uses curly brackets to set off what is done if the condition is true. Uses of if follow in the Examples section.

It is not strictly necessary to do what is called declaring variables, but we will try to follow the discipline of doing so. A declaration lets the JavaScript program “know” ahead of time the name of a variable. A variable is declared with the statement such as:

    var cost;

The var statement can also include an assignment statement. This is often called initialization because it sets the initial value of the variable.

    var total =0;

In programming, you often need to do something repeatedly. This is called looping in computing. JavaScript has the for compound statement for this purpose. It is a compound statement because it generally contains multiple statements. An example of a for loop would start out like this:

    for (i=0; i<n; i++) { one or more statements } 

This statement uses a variable named i and starts with i set to zero. If i is less than n, the statements between the curly brackets are executed. These statements might or might not make reference (use) the variable i. Next, the variable i is incremented by 1 and again compared to the value of the variable n. If i is less than n, the statements are executed again, with i now set to 1. This goes on until i is not less than n. You do not have to use the names given here. The increment or change does not have to be “adding 1,” which is what the ++ does. Similarly, the halting condition can be whatever makes sense for your situation. Looping, also called iteration, is a powerful tool.

The less than symbol (<) is one of several comparison operators. To make the test be: is i less than or equal to n, you use <=. You can figure out what > and >= mean. To test for equality, you use two equal signs put together: ==. The reason for this is that a single equal sign indicates assignment.

In your HTML files, you will put examples of individual JavaScript statements, and also define your own functions. Beginners tend to resist defining their own functions. Hopefully, the examples in the book will help you in your own work. Terms for running a function are invoking or executing or calling.

You can place the definition of functions anywhere inside a tag, but the standard place for client-side scripts is within <script> and </script> tags in the head section. You will use curly brackets to set off the function definitions. It is often the case that you have nesting of sections set off by curly brackets. Errors such as leaving off a closing bracket or putting one in the wrong place are commonplace and annoying. However, you can find and correct them by drawing lines from each opening bracket to the one that closes its section.

Some examples of JavaScript put in special delimiters to set off scripting. This prevents the older browsers that did not have the facility to interpret JavaScript from displaying the code. We show examples both with and without these delimiters.

A function can have an argument—that is, information to be used on a particular invocation of the function—more than one argument, or no arguments. Different types are shown here. If a function called movein is to use the string “ bird.gif”, the call would be:

    movein("bird.gif");

You define a function and you write a JavaScript statement that invokes the function. If the function does not have any arguments, the requirements of JavaScript are that you still use parentheses. Therefore, if you have defined a function called change, with no arguments, the call is:

    change();

Client-Side Events

The critical events discussed in this chapter include the submission of a form, moving the cursor over a certain area on the screen, moving the cursor out from a certain area, and clicking on the mouse. You define how these events are to be handled—that is, what the response is to be for these events—by assigning a quoted string containing the appropriate JavaScript code to certain variable names. These names are onSubmit, onMouseOver, onMouseOut, and onClick. Typically, the JavaScript code is a call to a JavaScript function you write. This is to make the code easier to read and to change.

You must specify timed events in a slightly different way in JavaScript. You will use strings of code that can be function calls, but there is not an analog to onMouseOver. To establish that a certain thing is to happen at a set interval of time, you invoke a function called setInterval. The first argument to the function is a string representing the JavaScript code. The second argument is the time interval, in milliseconds. Therefore, to specify that the function change is to be invoked every 800 milliseconds (somewhat less than every second), you write:

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

A variable, such as the tid indicated here, can be viewed as the name of this timing event. To stop responding to a particular timed event, you write:

    window.clearInterval(tid);

This means: For this window, stop checking for the timing event indicated by the value of tid.

At this point, you might be asking yourself, “how do I know when to define a function or a variable or an event?” The answer is first, that you learn by experience; and second, there is no one answer. Programming or scripting is like writing an essay or a story; it does not follow a set procedure.




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