JavaScript in LiveWire
LiveWire is an application development environment that uses JavaScript for creating server-based applications similar to CGI programs. In contrast to Navigator JavaScript, LiveWire JavaScript applications are compiled into bytecode executable files. These application executables are run in concert with a Netscape server (version 2.0 and later) that contains the LiveWire server extension.
The LiveWire server extension generates HTML dynamically; this HTML (which may also include client-side JavaScript statements) is then sent by the server over the network to the Navigator client, which displays the results. This process is illustrated in Figure 1.2.
JavaScript in LiveWire
For more information on LiveWire,
see the LiveWire
Developer's Guide.
In contrast to standard CGI programs, LiveWire JavaScript is integrated directly into HTML pages, facilitating rapid development and easy maintenance. LiveWire JavaScript contains an object framework that you can use to maintain data that persist across client requests, multiple clients, and multiple applications. LiveWire JavaScript also provides objects and methods for database access that serve as an interface to Structured Query Language (SQL) database servers.
JavaScript, the language
Part 2, "The JavaScript Language,"
describes the
common features of
client and server JavaScript.
As described in the previous sections, client and server JavaScript differ in numerous ways, but they have the following elements in common:
Embedding JavaScript in HTML
You can embed JavaScript in an HTML document in two ways:
That's all, folks.
A document can
have multiple
SCRIPT tags, and
each can enclose any
number of JavaScript
statements.
<SCRIPT>
JavaScript statements...
</SCRIPT>
The optional LANGUAGE attribute specifies the scripting language:
<SCRIPT LANGUAGE="JavaScript">
JavaScript statements...
</SCRIPT>
Unlike HTML, JavaScript is case sensitive.
Script hiding
Only Netscape Navigator versions 2.0 and later recognize JavaScript. To ensure that other browsers ignore JavaScript code, place the entire script within HTML comment tags, and precede the ending comment tag with a double-slash (//) that indicates a JavaScript single-line comment:
<SCRIPT>
<!-- Begin to hide script contents from old browsers.
JavaScript statements...
// End the hiding here. -->
</SCRIPT>
Since browsers typically ignore unknown tags, non-JavaScript-capable browsers will ignore the beginning and ending SCRIPT tags. All the script statements in between are enclosed in an HTML comment, so they are ignored too. Navigator properly interprets the SCRIPT tags and ignores the line in the script beginning with the double-slash (//).
Although you are not required to use this technique, it is considered good etiquette so that your pages don't generate unformatted script statements for those not using Navigator 2.0 or later.
Note
For simplicity, some of the examples in this book do not hide scripts, because the examples are written specifically for Navigator 2.0.
Example: a first script
Defining and calling functions
For a complete
description of
defining and calling
functions, see "Functions".
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure--a set of statements that performs a specific task. A function definition has three basic parts:
Event handlers are
introduced in
"Scripting event
handlers".
Generally, you should define the functions for a page in the HEAD portion of a document. That way, all functions are defined before any content is displayed. Otherwise, the user might perform an action while the page is still loading that triggers an event handler and calls an undefined function, leading to an error.
The following example defines a simple function in the HEAD of a document and then calls it in the BODY of the document:
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from old browsers
function square(number) {
return number * number
}
// End script hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
document.write("The function returned ", square(5), ".")
</SCRIPT>
<P> All done.
</BODY>
The function square takes one argument, called number. The function consists of one statement
that indicates to return the argument of the function multiplied by itself. The return statement specifies the value returned by the function. In the BODY of the document, the statement
return number * number
square(5)
calls the function with an argument of five. The function executes its statements and returns the value twenty-five. The script displays the following results:
The function returned 25.
All done.
The square function used the line
to display output in Navigator. This line calls the write method of the Navigator document object with JavaScript's standard object notation:
document.write(...)
objectName.methodName(arguments...)
where objectName is the name of the object, methodName is the name of the method, and arguments is a list of arguments to the method, separated by commas.
A method is a function associated with an object. You'll learn more about objects and methods in Chapter 7, "Object model." But right now, we will explore write a little more, because it is particularly useful.
Using the write method
As you saw in the previous example, the write method of document displays output in the Navigator. "Big deal," you say, "HTML already does that." But in a script you can do all kinds of things you can't do with ordinary HTML. For example, you can display text conditionally or based on variable arguments. For these reasons, write is one of the most often-used JavaScript methods.
The write method takes any number of string arguments that can be string literals or variables. You can also use the string concatenation operator (+) to create one string from several when using write.
Consider the following script, which generates dynamic HTML with Navigator JavaScript:
<HEAD> <SCRIPT>
<!--- Hide script from old browsers
// This function displays a horizontal bar of specified width
function bar(widthPct) {
document.write("<HR ALIGN='left' WIDTH=" + widthPct + "%>")
}
// This function displays a heading of specified level and some text
function output(headLevel, headText, text) {
document.write("<H", headLevel, ">", headText, "</H",
headLevel, "><P>", text)
}
// end script hiding from old browsers -->
</SCRIPT> </HEAD>
<BODY>
<SCRIPT>
<!--- hide script from old browsers
bar(25)
output(2, "JavaScript Rules!", "Using JavaScript is easy...")
// end script hiding from old browsers -->
</SCRIPT>
<P> This is some standard HTML, unlike the above that is generated.
</BODY>
The HEAD of this document defines two functions:
This is some standard HTML, unlike the above that is generated.
The following line creates the output of the bar function:
document.write("<HR ALIGN='left' WIDTH=", widthPct, "%>")
Notice that the definition of bar uses single quotation marks inside double quotation marks. You must do this whenever you want to indicate a quoted string inside a string literal. Then the call to bar with an argument of twenty-five produces output equivalent to the following HTML:
<HR ALIGN="left" WIDTH=25%>
write has a companion method, writeln, which adds a newline sequence (a carriage return or a carriage return and linefeed, depending on the platform) at the end of its output. Because HTML generally ignores newlines, there is no difference between write and writeln except inside tags such as PRE, which respect carriage returns.
Printing output
Navigator 2.0 does not print output created with JavaScript. For example, if you choose File|Print to print the page in the previous example, you see only the line that reads "This is some standard HTML...," even though you see both lines onscreen.
Displaying output
JavaScript in Navigator generates its results from the top of the page down. Once text has been displayed, you can't change it without reloading the page. In general, you cannot update part of a page without updating the entire page. However, you can update
If an event applies to an HTML tag, then you can define an event handler for it. The name of an event handler is the name of the event, preceded by "on." For example, the event handler for the focus event is onFocus.
To create an event handler for an HTML tag, add an event handler attribute to the tag; Put JavaScript code in quotation marks as the attribute value. The general syntax is
<TAG eventHandler="JavaScript Code">
where TAG is an HTML tag and eventHandler is the name of the event handler.
For example, suppose you have created a JavaScript function called compute. You can cause Navigator to perform this function when the user clicks a button by assigning the function call to the button's onClick event handler:
<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)">
You can put any JavaScript statements inside the quotation marks following onClick. These statements are executed when the user clicks the button. If you want to include more than one statement, separate statements with a semicolon (;).
Notice in the preceding example this.form
refers to the current form. The keyword this refers to the current object, which is the button. The construct this.form
then refers to the form containing the button. The onClick event handler is a call to the compute function, with the current form as the argument.
In general, it is good practice to define functions for your event handlers:
<INPUT TYPE="button" VALUE="Press Me" onClick="myfunc('astring')">Be sure to alternate double quotation marks with single quotation marks. Because event handlers in HTML must be enclosed in quotation marks, you must use single quotation marks to delimit string arguments. For example
<FORM NAME="myform"> <INPUT TYPE="button" NAME="Button1" VALUE="Open Sesame!" onClick="window.open('mydoc.html', 'newWin')"> </FORM>Alternatively, you can escape quotation marks by preceding them with a backslash (). You must use this technique if your code requires more than two levels of quoting.
<HEAD> <SCRIPT> <!--- Hide script from old browsers function compute(f) { if (confirm("Are you sure?")) f.result.value = eval(f.expr.value) else alert("Please come back again.") } // end hiding from old browsers --> </SCRIPT> </HEAD> <BODY> <FORM> Enter an expression: <INPUT TYPE="text" NAME="expr" SIZE=15 > <INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)"> <BR> Result: <INPUT TYPE="text" NAME="result" SIZE=15 > </FORM> </BODY>The display in Navigator will look like this:
Try entering some arithmetic expressions in the field and clicking the button.
The HEAD of the document defines a single function, compute, taking one argument, f, which is a form object. The function uses the Navigator JavaScript method confirm to display a Confirm dialog box with OK and Cancel buttons. If the user clicks OK, then confirm returns true, and the value of the result text field is set to the value ofeval(f.expr.value)
. The built-in JavaScript function eval evaluates its argument, which can be any string representing any JavaScript expression or statements.
If the user clicks Cancel, then confirm returns false and the alert method displays another message.
The form contains a button with an onClick event handler that calls the compute function. When the user clicks the button, JavaScript calls compute with the argument this.form
that denotes the current form object. In compute, this form is referred to as the argument f.
If you can't run server-based programs, skip this section.One of the most important uses of JavaScript is to validate form input to server-based programs such as LiveWire applications or CGI programs. This is useful because
<HEAD> <SCRIPT LANGUAGE="javascript"> function isaPosNum(s) { return (parseInt(s) > 0) }
function qty_check(item, min, max) { var returnVal = false if (!isaPosNum(item.value)) alert("Please enter a postive number" ) else if (parseInt(item.value) < min) alert("Please enter a " + item.name + " greater than " + min) else if (parseInt(item.value) > max) alert("Please enter a " + item.name + " less than " + max) else returnVal = true return returnVal }
function validateAndSubmit(theform) { if (qty_check(theform.quantity, 0, 999)) { alert("Order has been Submitted") theform.submit() }|else alert("Sorry, Order Cannot Be Submitted!") } </SCRIPT> </HEAD>isaPosNum is a simple function that returns true if its argument is a positive number, and false otherwise. qty_check takes three arguments: an object corresponding to the form element being validated (item) and the minimum and maximum allowable values for the item (min and max). It checks that the value of item is a number between min and max and displays an alert if it is not. validateAndSubmit takes a form object as its argument; it uses qty_check to check the value of the form element and submits the form if the input value is valid. Otherwise, it displays an alert and does not submit the form.
<BODY> <FORM NAME="widget_order" ACTION="lwapp.html" METHOD="post"> How many widgets today? <INPUT TYPE="text" NAME="quantity" onChange="qty_check(this, 0, 999)"> <BR> <INPUT TYPE="button" VALUE="Enter Order" onClick="validateAndSubmit(this.form)"> </FORM> </BODY>This form submits the values to a page in a LiveWire application called
lwapp.html
. It also could be used to submit the form to a CGI program.
The form looks like this:
Try entering some numbers, and see how the script reacts. (Note: this example does not actually submit the order to a server-based program (lwapp.html), as shown in the example code.)
The onChange event handler is triggered when you change the value in the text field and move focus from the field by either pressing the Tab key or clicking the mouse outside the field. Notice that both event handlers use this to represent the current object: in the text field, it is used to pass the JavaScript object corresponding to the text field to qty_check, and in the button it is used to pass the JavaScript form object to validateAndSubmit. To submit the form to the server-based program, this example uses a button that calls validateAndSubmit, which submits the form using the submit method, if the data are valid. You can also use a submit button (defined by<INPUT TYPE="submit">
) with an onSubmit event handler that returns false if the data are not valid. For example,
<INPUT TYPE="submit" onSubmit="qty_check(theform.quantity, 0, 999)"When qty_check returns false if the data are invalid, the onSubmit handler will prohibit the form from being submitted.