Sie sind auf Seite 1von 73

VBScript Language for IV Year IT Students

E-Commerce
Electronic Commerce - the use of Web sites to sell goods and services over the Internet. The World Wide Web (Web) - a body of software and a set of protocols and conventions based on hypertext and multimedia that make the Internet easy to use and browse. hypertext - a capability to jump between and within documents virtually at will. client/server computing - processing is shared between multiple small computers known as clients that are connected via a network to a host computer known as a server. uniform resource locator (URL) protocol that allows your browser to communicate with remote hosts.
2

When displaying information sent to it from the server, the browser processes formatting instructions included in the text file retrieved from the server. The server stores the data with tags to indicate how text and other forms of information will be displayed. The tags in the World Wide Web are part of a special publishing language called hypertext markup language (HTML). Documents on the Web are referred to as Web pages and their location is a Web site. Since HTML is standard for all computers, any Web browser can request an HTML document from any Web server.

Displaying Information with a Browser

Commonly Used HTML tags


Tag <B> <I> <CENTER> <BR> <HTML> <TITLE> Operation Boldface text Italicized text Centered text Line Break Begin/End HTML Begin/End Title of Web Page Example <B>Hello</B> <I>Hello</I> <CENTER>Hello</CEN TER> End this line.<BR> Start another line. <HTML></HTML> <TITLE>Web page for CH. 13</TITLE> Hello Hello Hello End this line. Start another line. Begins and Ends Web Page Web page for CH. 13 appears in header bar of browser. Result

Commonly Used HTML tags (Cont.)


Tag <BODY> <P> <H1> Operation Begin/End Body of Web page Start/End paragraph Create type 1 (largest) heading (also 2, 3, 4) Example <BODY></BODY> <P>Paragraph</P><P>New Paragraph</P> <H1>Biggest</H1> <H2>Big</H2> <H4>Smallest</H4> <image src = family.jpg> <FORM NAME = Order></FORM> <INPUT TYPE = text NAME = txtOrder> Result Begins and ends the body of the web page Paragraph New Paragraph

Biggest
Big
Smallest

<IMG SRC Include image in = > web page <FORM> Create an input form on a web page Create text box for input

jpg image file named family is displayed Creates an input form named Order A text box for input is displayed

<INPUT TYPE = text>

Notes About HTML


HTML tags are enclosed in angle brackets (< >) to set them off. Most HTML tags work in pairs, but there are some exceptions. Script placed within the <HEAD>..</HEAD> tags is not executed unless referred to in the body of the HTML page. Script placed in the body is automatically executed as the Web page is loaded into the browser.
6

General Form of Web Page


<HTML> <HEAD> <TITLE> Title of Web page goes here </TITLE> Other heading material goes here </HEAD> <BODY> Body of Web page goes here </BODY> </HTML>

Scripting in the Browser


An important use of Web browsers in electronic commerce is to enter information. Validation of input and calculations on the browser can be carried out via a type of computer programming known as scripting. Scripting is similar to other types of computer programming in that it uses variables and statements to carry out a desired set of logical operations, but it is also different. Instead of being executed as a compiled program, it is executed by another program, in our case the Web browser. Scripting languages are easier to work with than compiled languages. A script takes longer to run than a compiled program since each instruction is being interpreted rather than being executed directly by the processor.

Scripting Languages
The two most widely used scripting languages for working with Web pages are Javascript and VBScript. Javascript uses a C-like syntax and can run on either Netscape or Internet Explorer browsers. VBScript is based on Visual Basic, but runs only on Internet Explorer. Both Javascript and VBScript, when used on the browser, are termed client-side scripting since they are running on the Web client. VBScript is also widely used in the Active Server Page (ASP) approach to directing Microsoft Web server software that runs on Windows NT or 2000 operating systems. This is called server-side scripting.

What is VBScript?
An interpreted programming language primarily used to write relatively short programs that access operating system and application objects. Such languages are referred to as "scripting" languages. The VBScript commands are a subset of the more complete, compiled Visual Basic language.

Why is VBScript used?


VBScript is an easy to learn language and thus is a good candidate for a brief introduction to programming. VBScript, VB, and VBA (Visual Basic for Applications) are collectively used more than any other language in the world so exposure to these languages is important. VBScript can be used to automate tasks in web pages, MS Excel spreadsheets, MS Access Databases, and other MS applications. VBScript can be used to automate administrative tasks such as moving or copying files, creating user accounts, etc.

Creating/Editing a VBScript file


VBScript programs are ASCII text files and can be edited using any text editor such as notepad.exe or pfe.exe. Open your ITEC 110 student folder and create a folder named lab2 within it. As was discusses in lab 1 please verify that the tools>folder options->view tab->hide file extensions for known file types is NOT checked. Open the lab2 folder. Right click anywhere in the folder and choose "new text file" from the resulting drop down menu. Rename the new text file to HelloWorld.vbs . Right click on the new file, choose EDIT, and enter the VBScript program on the next slide.

What is VBScript
Based on the Visual Basic family of languages Supports object oriented features Interpreted Loosely Typed Implicitly Declared

Visual Basic & VBScript


Visual Basic
Stand-alone (compiled or interpreted) Variables are typed

VBScript
Embedded in a Web page and executed by browser Variables can be associated with any type Uses most program structures available in VB, including loops and decisions

Contents
Syntax Rules Comments Naming Rules Data Types Storage
Variables, Constants, Arrays Arithmetic, Comparison, Logical, Assignment, Concatenation If Select While DoWhile For Built-In User defined

Operators

Branching Looping

Sub/Functions

Syntax Rules
VBScript is not case sensitive
Except for strings (denoted by double-quotes)

Each statement can only exist on one line


Unless you use a line continuation

Statements can be either simple statements or compound statements

Comments
Rem commented statement commented statement

Can be a complete line or a portion of a line. VBScript does not support multi-line comments. The comment symbol must be put at the start of each comment.

Naming Rules
1. Must begin with a letter or the underscore
Good: count, strInfo, _data Bad: 2day, 4get, *count violate this rule.

2. Cannot contain special characters except the underscore


Good: Names using alphabets, numbers and the underscore. Bad: Names using symbols and other special characters.

3. Cannot match a reserved word


Bad: for, if, Select

4. Must be unique within a context 5. Must be less than 256 characters

Naming Convention
objDescriptiveName

obj
Three letter prefix for the data type

DescriptiveName
A descriptive name for the variable First letter of each word in upper case

Literal Types
Numeric
1 3.14 3E7

Boolean
True False

Characters
Hello World 123 Straw Lane 43210

Date
#07/21/2006# #Jan 6, 2008#

Variables
Dim variableName

Variables hold values that can change during program execution They function just like temporary storage locations Declaration of variables is optional, but recommended

Constants
Const constantName = value

Constant names hold values that cannot change during program execution Constants should be used in place of hardcoded values

Operations
Operations are the many forms of computations, comparisons etc that can be performed in VB Most operations are binary in the form: operand1 operator operand2 Other operations are unary in the form operator operand1 When an operator has 2 symbols, you cannot separate them with a space:
Good: 2 <> 3 Bad: 2 < > 3

Arithmetic
Used to perform calculations Both operands must be numeric values The result is a numeric value + * / \ ^ Mod Addition Subtraction, Negation Multiplication Division Integer Division Exponent Modulo

Comparison
Used to compare the value of two items Both operands must be of the same data type The result is a Boolean value = <> < > <= >= Equality Inequality Less than Greater than Less than or equals Greater than or equals

Logical
Used to reduce Boolean values into a single Boolean value Both operands must be Boolean values The result is a Boolean value

And Or Not Xor

Conjunction Disjunction Negation Exclusion

And Truth Table


Conjunction Used when both conditions are required

Operand1 T T F F

Operand2 T F T F

Result T F F F

Or Truth Table
Disjunction Used when either condition is sufficient

Operand1 T T F F

Operand2 T F T F

Result T T T F

Not Truth Table


Unary Operand Used to change the value of a condition

Operand 1 T F

Result F T

Xor Truth Table


Exclusion Used when either condition should be different

Operand1 T T F F

Operand2 T F T F

Result F T T F

Assignment
Changes the value of a variable = Uses the same symbol as an equality check operator. Assignment only occurs when used in any of the following forms: variable = literal value variable = expression variable = variable

Concatenation
Combines 2 data types for display as a string &

Branching
Allows you to avoid running certain sections of your code Code is only executed when a condition (or conditions) evaluate to True Provides a single application the ability to react differently to different input values

If
If condition Then statement(s) End If

Performs an operation only if the condition evaluates to True Used when an action is either performed or not performed.

IfElse
If condition Then statement(s) Else statement(s) End If

Performs the If portion only if the condition evaluates to True and the Else portion otherwise. Used in an either or scenario when an operation is always performed.

IfElseIf
If condition1 Then statement(s) ElseIf condition2 Then statement(s) Else statement(s) End If

Only one section can be executed even if many conditions evaluate to True. Used in a multiple choice scenario Inclusion of the last Else is optional

Select
Select Case variable statement(s) Case value1 statement(s) Case value2 statement(s) Case Else statement(s) End Select

Used to choose between 1 of several discrete values for a variable. Inclusion of Case Else is optional Less powerful compared to the If statement

Loops
Allows you to repeat running certain sections of your code Code executes when a condition (or conditions) evaluate to True Be careful with Loops. They can result in infinite processing. Forms
Entry Condition
Entry only when a initial condition is met

Iterated
Repeats for a specific number of times

Loops: Cautionary Items


1. Can this loop ever be entered
If no, then you dont need the loop

2. Can this loop ever be exited


If no, then you have an infinite loop

Loop: Parts
1. Where does the loop start?
Expressed as an assignment

2. When does the loop end?


Expressed as a condition

3. How is the loop variable altered?


Expressed as an arithmetic operation Ensure that you are increasing/decreasing properly

While
While condition statement(s) Wend

Entry Condition Loop Simplest form of the loop Requires manual modification of the loop condition

For
For variable = start To finish [Step change] statement(s) Next

Iterated Loop Favored because all the loop details are in the definition statement

Function
Function functionName(parameter list) statement(s) functionName = value End Function

Block of code used to perform an operation Both VBScript and QTP provide a large number of built-in functions You can add your own built-in functions to the list

Best Practices
Comment liberally Use a naming convention Avoid mixing cases Indent your code

VBScript Examples

VBScript Examples
Greeting (printing to message box) Greeting 2 (printing to current window) Speed Check (Dicision) Blast Off! (FOR loop) Varying Font (FOR loop) Speed Check 2 (event handler) Speed Check 2B (alternate code) Get User Input Heart Beat (calculation in event handler) Heart Beat 2 (arguments to event handler)

Greeting
<html> <head> <title>VBScript Demo</title> </head> <body> <h1>VBScript Demo</h1> <script language="VBScript"> <!-Dim name Dim age name = "Jack" age = 20 MsgBox "Hello, " & name & ". Are you " _ & age & " years old? --> Try it. </script> </html>

Greeting 2
<html> <head> <title>VBScript Demo</title> </head> <body> <h1>VBScript Demo</h1> <script language="VBScript"> <!-Dim name Dim age name = "Jack" age = 20 document.Write "Hello, " & name & ". & age & " years old? --> </script> </html>

Are you " _

Try it.

<body> <h1>Speed Check</h1> <script language="VBScript"> Dim yourSpeed Dim diff Dim message const maxSpeed = 50

Speed Check (Decision)

yourSpeed = 60 message = "Your Speed is " & yourSpeed & " mph." diff = yourSpeed - maxSpeed If diff > 0 Then message = message & " You are speeding by " & diff & " mph." Else message = message & "You are under the speed limit." End If MsgBox message </script> </body> </html> Try it.

Blast Off! (For Loop)


<html> <head> <title>VBScript Demo</title> </head> <body> <h1>For Loop Demo</h1> <script language="VBScript"> Dim num For num = 10 To 1 Step -1 document.write(num & "!" & "<br>") Next document.write("Blast Off!") </script> </html>

Try it.

Varying Font (For Loop)


... <body> <h1>For Loop Demo</h1> <script language="VBScript"> Dim num For num = 1 To 6 document.write("<font color='red' size=" & _ num & ">") document.write("<i>This sentence was & _ generated by VBScript.</i>") document.write("</font><br>") Next Try it. </script> </html>

Events
Event: An action by the user--e.g., mouse-click, mouse-move, etc.that triggers execution of a code known as event handler Event Handler: Piece of programming code, written in VBScript, Javascript, Java, etc., allowing the page to react to user input

Event Examples
Event Name
onClick onDblClick onMouseMove onMouseOut onMouseOver onLoad

Example
Mouse button clicked on textbox Button double-clicked on textbox doubleMouse is moved Mouse pointer leaves image area Mouse pointer first enters image area Web page is loaded

<head> <script language="VBScript"> <!-OnClick -- Subprogram Greeting goes here ---> </script> </head>

Event

<body> <h1>onClick Demo</h1> <form name="theForm"> Enter your name. <input type="text" name="myName" size=20"> <input type="button" value="Click Me" onClick="Greeting()"? </form> </body>

Subprogram Greeting
<html> <head> <script language="VBScript"> <!-Sub Greetings() MsgBox "Welcome, " & theForm.myName.value End Sub --> </script> </head> <body> </body> </html>

... <body> <h1>Speed Check</h1>

(Recall) Speed Check

<script language="VBScript"> Dim yourSpeed Dim diff Dim message const maxSpeed = 50 yourSpeed = 60 message = "Your Speed is " & yourSpeed & " mph." diff = yourSpeed - maxSpeed If diff > 0 Then message = message & " You are speeding by " & diff & " mph." Else message = message & "You are under the speed limit." End If MsgBox message </script> </body>

</html>

Try it.

Speed Check 2 (Event Handler)


<html> <head> <title>VBScript Demo</title> <script language="VBScript"> <! Insert event procedure code here. --> </script> </head> <body> <h1>Speed Check</h1> <form name="myForm"> <input type="button" name="start" value="Click Me" onClick="CheckSpeed()"> </form> </body> </html>

Try it.

Speed Check 2 (Event Handler)


<script language="VBScript"> <!-Sub CheckSpeed() Dim yourSpeed Dim diff Dim message const maxSpeed = 50 yourSpeed = 60 message = "Your Speed is " & yourSpeed & " mph." diff = yourSpeed - maxSpeed If diff > 0 Then message = message & " You are speeding by " & diff & " mph." Else message = message & "You are under the speed limit." End If MsgBox message End Sub --> </script>

Speed Check 2B (Alternate Code)


<html> <head> <title>VBScript Demo</title> <script language="VBScript"> <!-Insert Alternate code for event procedure here. --> </script> </head> <body> <h1>Speed Check</h1> <form name="myForm"> <input type="button" name="btnStart" value="Click Me"> </form> </body> </html>

Try it.

Get User Input


<html> <head> <script language=VBScript> . . . Code for GreetUser() goes here </script> </head> <body> <h1>Get User Information Demo</h1> <form name="myForm"> Please enter your name. <input type="text" name="myName" size="10"><br> Please enter your age. <input type="text" name="myAge" size="3"><br> <p> <input type="button" name="start" value="Click Me" onClick="GreetUser()"> </form> Try it. </body> </html>

GreetUser()
<head> <script language=VBScript> <!-Option Explicit Sub GreetUser() Dim message message = "Welcome to the world of VBScript, " & _ myForm.myName.value & "!" message = message & " Are you really " & _ myForm.myAge.value & " years old?" MsgBox message End Sub

- -> </script> </head>

GreetUser() Version 2
<script language=VBScript> <!-Option Explicit Sub GreetUser() Dim message message = "Welcome to the world of VBScript, " & _ myForm.myName.value & "!" message = message & " Are you really " & _ myForm.myAge.value & " years old?" document.Write (message) End Sub- ->

</script>

Try it.

GreetUser() Version 3
<script language=VBScript> <!-Option Explicit Sub GreetUser() Dim message message = "Welcome to the world of VBScript, " & _ myForm.myName.value & "!" message = message & " Are you really " & _ myForm.myAge.value & " years old?" document.write("<h1><font color='blue'>Welcome & _ Message</font></h1>") document.write(message) End Sub - -> Try it. </script>

Heart Beat (Calculaton)


<html> <head> <title>VBScript Calculaton Demo</title> <script language="VBScript"> <! Insert code for CalcuHeartBeat() here. --> </script> </head> <body> <h2>How Many Times Have My Heart Beaten So Far?</h2> <form name="myForm"> Please enter your age. <input type="text" name="txtAge" size="3"><br> <input type="button" name="btnStart" value="Calculate" onClick="CalcHeartBeat()"> </form> </body> Try </html>

it.

Heart Beat (Calculaton)


<!-Sub CalcHeartBeat() const daysPerYear = 365 const hoursPerDay = 24 const minutesPerHour = 60 const beatsPerMin = 70 Dim totalBeats Dim years years = document.myForm.txtAge.value totalBeats = years * daysPerYear * hoursPerDay * _ minutesPerHour * beatsPerMin message = "If your are " & years & " years old, " & _ "then your heart has beaten " & totalBeats & " times so far." MsgBox message End Sub --> </script>

Heart Beat 2 (Using argument)


<html> <head> <title>VBScript Calculaton Demo</title> <script language="VBScript"> <! Insert code for CalcHeatBeat(years) here. --> </script> </head> <body> <h2>How Many Times Have My Heart Beaten So Far?</h2> <form name="myForm"> Please enter your age. <input type="text" name="txtAge" size="3"><br> <input type="button" name="btnStart" value="Calculate" onClick="CalcHeartBeat(myForm.txtAge.value)"> </form> </body> Try </html>

it.

Heart Beat 2 (Using argument)


<script language="VBScript"> <!-Sub CalcHeartBeat(years) const daysPerYear = 365 const hoursPerDay = 24 const minutesPerHour = 60 const beatsPerMin = 70 Dim totalBeats totalBeats = years * daysPerYear * hoursPerDay * _ minutesPerHour * beatsPerMin message = "If your are " & years & " years old, " & _ "then your heart has beaten " & totalBeats & " times so far." MsgBox message End Sub --> </script>

onMouseOut (Using argument)


<html> <head> <title>VBScript Calculaton Demo</title> <script language="VBScript"> <! Insert code for Greet(msg) here. --> </script> </head> <body> <h1>onMouseOver & onMouseOut Demo</h1> <form name=myForm> Hover the cursor over the text box, then move it away.<br> <input type="text" name="txtName" onMouseOver="Greet('Hello!')" onMouseOut="Greet('Good-bye!')"> </form> </body> </html>

Try it.

onMouseOut (Using argument)


<head> <script language="VBScript"> <!-Sub Greet(msg) document.myForm.txtName.value = msg End Sub --> </script> </head>

Three Buttons & One Subprocedure


<head> <script language="VBScript"> <!--- Insert Subprogram ChangeBackground(color) here End Sub --> </script> </head> <body> <h1>Changing BG Color with One Subprocedure</h1> <form> <input type="button" value="To Blue Background " onClick="ChangeBackground('blue')"> <input type="button" value="To Yellow Background" onClick="ChangeBackground('yellow')"> <input type="button" value="To Red Background onClick="ChangeBackground('red')"> </body>

Three Buttons & One Subprocedure


<head> <script language="VBScript"> <!-Sub ChangeBackground(color) document.write("<html><head><title>Demo</title></head>") document.write("<body bgcolor='" & color & "'>") document.write("<h1><font color='white'>Background Demo _ & </font></h1>") document.write("</body></html>") End Sub --> </script> </head>

Your Turn
Write an HTML page in which:
The user is asked to input in a form ones name . When a button is clicked, a greeting which is appropriate for the current timeGood morning, Good afternoon, or Good eveningis displayed along with the users name.

Your Turn (2)


Write an HTML page in which:
The user is asked to input in a form ones name and a purchase price at a gift shop. When a button is clicked, the luxury tax on the price is calculated according to the following formula:
For price < $100, tax rate = 0% For price >= $100, tax rate = 6%

A message box displays the users name, price, tax, and the total.

Das könnte Ihnen auch gefallen