Microsoft Visual Basic Scripting Edition

Calculator

How does this sample work? Essentially, the calculator is an HTML table containing button controls. The buttons themselves are intrinsic INPUT style buttons, not ActiveX controls. VBScript code is attached to the OnClick event for these buttons. The display is simply an intrinsic INPUT style text box.

This sample demonstrates both ways of hooking up code to events on controls.

The first way is to specify the name of the procedure in the tag for the button itself. All of the numeric buttons use this to call the same event procedure, passing in the appropriate value. For example:

	
	<INPUT NAME="Seven" TYPE="Button" VALUE="  7  " OnClick="NumPressed(7)">
Here the NumPressed procedure is called with the value of 7.

The second way is to use Visual Basic-style event procedures, and this is how the other buttons are implemented. For example, the Clear Entry (CE) button does not have an explicit reference to code:

	
	<INPUT NAME="ClearEntry" TYPE="Button" VALUE="  CE ">
Instead, Internet Explorer automagically hooks up the events with the appropriate code, by looking for a procedure in the Script tag with a name of the form OBJECTNAME_EVENTNAME

For example, this event procedure is called whenever the onClick event occurs for the ClearEntry control:

	
Sub ClearEntry_onClick()
' Remove current number and reset state
    Document.Keypad.ReadOut.Value = "0"
    FlagNewNum = True
End Sub
Also, notice the variable declared at the beginning of the Script tag, outside of any procedure:
	
<SCRIPT LANGUAGE="VBScript">
<!-- 
' Module-level variables
Dim Accum		' Previous number (operand) awaiting operation
Dim FlagNewNum		' Flag to indicate a new number (operand) is being entered
Dim PendingOp		' Pending operation waiting for completion of second operand
. . .
These are "module-level" variables that persist for as long as the page is loaded. By contrast, variables declared within a procedure cease to exist as soon as the procedure exits. Thus module-level variables can be used to store values that must persist between invocations of a procedure. Module-level variables are also visible to all procedures, and so are useful when multiple procedures need to share values.

Finally, note the extensive use of the CDbl() runtime function, which converts numeric or string values to floating point, and CStr() which converts numeric values to strings. While these aren't strictly required (VBScript's variants will interconvert between the various types as needed) good coding practice suggests they be used to assert the expected type and to make the code more self-documenting.