72
1 Client-Side Scripting with VBScript

Client-Side Scripting with VBScript - Amar Singh College ... · VBScript: Client Side Scripting VBScript was created to allow web page developers the ability to create dynamic web

Embed Size (px)

Citation preview

1

Client-Side Scripting with VBScript

2

Introduction

Visual Basic Script (VBScript) Subset of Microsoft Visual Basic IE contains VBScript scripting engine (interpreter) Similar to JavaScript

JavaScript used more for client-side scripting

VBScript de facto language for ASP (Active Server Pages)

VBScript: Client Side Scripting

VBScript was created to allow web page developers the ability to create dynamic web pages for their viewers who used Internet Explorer. With HTML, not a lot can be done to make a web page interactive, but VBScript unlocked many tools like: the ability to print the current date and time, access to the web servers file system, and allow advanced web programmers to develop web applications.

3

VBScript: Why Learn and Use It?

VBScript is a prerequisite for ASP developers and should be learned thoroughly before attempting any sophisticated ASP programming. Programmers who have used Visual Basic in the past will feel more at home when designing their dynamic web pages with VBScript, but it should be known that only visitor's using Internet Explorer will be able to access your code, while other browsers will not be able to process the VBScript code.

4

Do's & Don'tsDO Learn VBScript

If you have a solid understanding of HTML If you want to program successfully in ASP If you already know Visual Basic and would like to experiment

with VBScript If you are a hobbyist that enjoys knowing many programming

DON'T Learn VBScript If you are developing a web page for the general public If your site has visitors who use a browser other that Internet

Explorer If prefer to avoid dying languages. If you want something more supported, you should learn

Javascript.

5

VBScript Installation VBScript is a client side scripting language that

can be developed in any text editor. An example of a text editor would be Notepad. VBScript is a Microsoft proprietary language that

does not work outside of Microsoft programs.

6

After you have written your VBScript code you need the Internet Explorer to process your code.

Firefox, Opera, Netscape, etc will not be able to run VBScript.

VBScript Supported Browsers

VBScript First Script

document.write("Hello World")

7

VBScript Tag

The HTML script tag lets the browser know we are going to use a script and the attribute typespecifies which scripting language we are using. VBScript's type is "text/vbscript".

All the VBScript code that you write must be contained within script tags, otherwise they will not function properly.

No Semicolons! VBScript Multiple Line Syntax

Microsoft has included a special character for the multiple lines of code: the underscore "_".

8

VBScript Variables

Variable is a named memory location used to hold a value that can be changed during the script execution. VBScript has only ONE fundamental data type, Variant.Rules for Declaring Variables: Variable Name must begin with an alphabet. Variable names cannot exceed 255 characters. Variables Should NOT contain a period(.) Variable Names should be unique in the declared

context.

9

Declaring Variables

Variables are declared using dim keyword. Since there is only ONE fundamental data type, all the declared variables are variant by default. Hence, a user NEED NOT mention the type of data during declaration.Example 1: In this Example, Var can be used as a String, Integer or even arrays.

Dim Var Example 2: Two or more declarations are separated by comma(,)

Dim Variable1,Variable2

10

Declaring Variables in VBScript

Dim myVariable1 Dim myVariable2 Dim myVariable3, myVariable4

11

Dim myVariable1, myVariable2myVariable1 = 22myVariable2 = "Howdy"document.write("My number is " & myVariable1)document.write("My string is " & myVariable2)

Assigning Values to the Variables

Values are assigned similar to an algebraic expression. The variable name on the left hand side followed by an equal to (=) symbol and then its value on the right hand side.Rules : The numeric values should be declared without

double quotes. The String values should be enclosed within

doublequotes(") Date and Time variables should be enclosed

within hash symbol(#)

12

Examples

' Below Example, The value 25 is assigned to the variable.Value1 = 25

' A String Value VBScript is assigned to the variable StrValue.StrValue = VBScript

' The date 01/01/2020 is assigned to the variable DToday.Date1 = #01/01/2020#

' A Specific Time Stamp is assigned to a variable in the below example.Time1 = #12:30:44 PM#

13

Scope of the Variables

Variables can be declared using the following statements that determines the scope of the variable. The scope of the variable plays a crucial role when used within a procedure or classes. Dim Public Private

14

Scope of the Variables - Dim

Variables declared using Dim keyword at a Procedure level are available only within the same procedure. Variables declared using Dim Keyword at script level are available to all the procedures within the same script.

Example : In the below example, the value of Var1 and Var2 are declared at script level while Var3 is declared at procedure level.

15

16

Dim Var1

Dim Var2

Call add()

Function add()

Var1 = 10

Var2 = 15

Dim Var3

Var3 = Var1+Var2

Msgbox Var3 'Displays 25, the sum of two values.

End Function

Msgbox Var1 ' Displays 10 as Var1 is declared at Script level

Msgbox Var2 ' Displays 15 as Var2 is declared at Script level

Msgbox Var3 ' Var3 has No Scope outside the procedure. Prints Empty

Scope of the Variables - PUBLIC

Variables declared using "Public" Keyword are available to all the procedures across all the associated scripts. When declaring a variable of type "public", Dim keyword is replaced by "Public".

Example : In the below example, Var1 and Var2 are available at script level while Var3 is available across the associated scripts and procedures as it is declared as Public.

17

18

Dim Var1

Dim Var2

Public Var3

Call add()

Function add()

Var1 = 10

Var2 = 15

Var3 = Var1+Var2

Msgbox Var3 'Displays 25, the sum of two values.

End Function

Msgbox Var1 ' Displays 10 as Var1 is declared at Script level

Msgbox Var2 ' Displays 15 as Var2 is declared at Script level

Msgbox Var3 ' Displays 25 as Var3 is declared as Public

Scope of the Variables - PRIVATE

Variables that are declared as "Private" have scope only within that script in which they are declared. When declaring a variable of type "Private", Dim keyword is replaced by "Private".

Example : In the below example, Var1 and Var2 are available at Script Level. Var3 is declared as Private and it is available only for this particular script. Use of "Private" Variables is more pronounced within the Class.

19

20

Dim Var1

Dim Var2

Private Var3

Call add()

Function add()

Var1 = 10

Var2 = 15

Var3 = Var1+Var2

Msgbox Var3 'Displays the sum of two values.

End Function

Msgbox Var1 ' Displays 10 as Var1 is declared at Script level

Msgbox Var2 ' Displays 15 as Var2 is declared at Script level

Msgbox Var3 ' Displays 25 but Var3 is available only for this script.

VBScript Constants

Constant is a named memory location used to hold a value that CANNOT be changed during the script execution.

If a user tries to change a Constant Value, the Script execution ends up with an error.

Constants are declared the same way the variables are declared.

21

Declaring Constants

Syntax:[Public | Private] Const Constant_Name = Value

The Constant can be of type Public or Private. The Use of Public or Private is Optional. The Public constants are available for all the

scripts and procedures while the Private Constants are available within the procedure or Class.

One can assign any value such as number, String or Date to the declared Constant.

22

23

Dim intRadius

intRadius = 20

const pi=3.14

Area = pi*intRadius*intRadius

Msgbox Area

24

Operators

VBScript Not case-sensitive Provides arithmetic operators, logical operators,

concatenation operators, comparison operators and relational operators

Arithmetic operators Similar to JavaScript arithmetic operators Division operator

\

Returns integer result Exponentiation operator

^

Raises a value to a power

25

Operators

Arithmetic operatorsVBScript operation Arithmetic

operator Algebraic expression

VBScript expression

Addition + x + y x + y Subtraction - z 8 z 8 Multiplication * yb y * b Division (floating-point) / v u or v / u

Division (integer) \ none u \ u

Exponentiation ^ qp Q ^ p

Negation - -e -e

Modulus Mod q mod r q Mod r

VBScript operation

Arithmetic operator

Algebraic expression

VBScript expression

Addition

+

x + y

x + y

Subtraction

-

z 8

z 8

Multiplication

*

yb

y * b

Division (floating-point)

/

v u or

v / u

Division (integer)

\

none

u \ u

Exponentiation

^

qp

Q ^ p

Negation

-

-e

-e

Modulus

Mod

q mod r

q Mod r

26

Operators

Comparison operatorsStandard a lgebra ic equa lity opera tor or rela tiona l opera tor

VBSc rip t c omparison opera tor

Example of VBSc rip t c ond ition

Meaning of VBSc rip t c ond ition

= = d = g d is equal to g s r s is not equal to r > > y > x y is greater than x < < p < m p is less than m >= c >= z c is greater than or equal to z

y > x

y is greater than x

p class="tB"/p

p class="tB"p < m/p

p class="tB"p is less than m/p

p class="tB"(/p

p class="tB"=/p

p class="tB"c >= z

c is greater than or equal to z

(

27

Operators Comparison operators

Only symbols for equality operator (=) and inequality operator () differ from JavaScript

Can also be used to compare strings Logical operators

And (logical AND)Or (logical OR)Not (logical negation)Imp (logical implication)Xor (exclusive OR)Eqv (logical equivalence)

28

Operators

Truth tables for VBScript logical operatorsTruth tab les for VBSc rip t Log ic a l Opera tors Logical And: True And True = True True And False = False False And True = False False And False = False

Logical Or: True Or True = True True Or False = True False Or True = True False Or False = False

Logical Imp: True Imp True = True True Imp False = False False Imp True = True False Imp False = True

Logical Eqv: True Eqv True = True True Eqv False = False False Eqv True = False False Eqv False = True

Logical Xor: True Xor True = False True Xor False = True False Xor True = True False Xor False = False

Logical Not: Not True = False Not False = True

Truth tables for VBScript Logical Operators

Logical And:

True And True = True

True And False = False

False And True = False

False And False = False

Logical Or:

True Or True = True

True Or False = True

False Or True = True

False Or False = False

Logical Imp:

True Imp True = True

True Imp False = False

False Imp True = True

False Imp False = True

Logical Eqv:

True Eqv True = True

True Eqv False = False

False Eqv True = False

False Eqv False = True

Logical Xor:

True Xor True = False

True Xor False = True

False Xor True = True

False Xor False = False

Logical Not:

Not True = False

Not False = True

29

Operators

String concatenation Plus sign, + Ampersand, &

Formally called string concatenation operator If both operands are strings, + and & can be used

interchangeably s3 = s1 & s2 s3 = s1 + s2

If varying data types, use ampersand (&) Error: s1 = hello + 22

Dim myStringmyString = "Hello there!"myString = myString & " My name"myString = myString & " is Frederick"myString = myString & " Nelson."document.write(myString)

30

VBScript Arrays

When a series of values are stored in a single variable, then it is known as array variable.

31

Array Declaration :

Arrays are declared the same way a variable has been declared except that the declaration of an array variable uses parenthesis.

'Method 1 : Using Dim

Dim arr1() 'Without Size

'Method 2 : Mentioning the Size

Dim arr2(5) 'Declared with size of 5

'Method 3 : using 'Array' Parameter

Dim arr3

arr3 = Array("apple","Orange","Grapes")

1. Although, the Array size is indicated as 5, it can hold 6 values as array index starts from ZERO.

2. Array Index Cannot be Negative.3. VBScript Arrays can store any type of variable in

an array. Hence, an array can store an integer, string or characters in a single array variable.

4. The values are assigned to the array by specifying array index value against each one of the values to be assigned. It can be a string.

32

33

Dim arr(5)

arr(0) = "1" 'Number as String

arr(1) = "VBScript" 'String

arr(2) = 100 'Number

arr(3) = 2.45 'Decimal Number

arr(4) = #10/07/2013# 'Date

arr(5) = #12.45 PM# 'Time

document.write("Value stored in Array index 0 : " & arr(0) & "")

document.write("Value stored in Array index 1 : " & arr(1) & "")

document.write("Value stored in Array index 2 : " & arr(2) & "")

document.write("Value stored in Array index 3 : " & arr(3) & "")

document.write("Value stored in Array index 4 : " & arr(4) & "")

document.write("Value stored in Array index 5 : " & arr(5) & "")

VBScript - Decision Making

Decision making allows programmers to control the execution flow of a script or one of its sections. The execution is governed by one or more conditional statements.

34

Statement Description

if statementAn if statement consists of a booleanexpression followed by one or more statements.

if..else statement

An if else statement consists of a booleanexpression followed by one or more statements. If the condition is True, the statements under If statements are executed. If the condition is false, Else part of the script is Executed

if...elseif..else statement

An if statement followed by one or more ElseIf Statements, that consists of boolean expressions and then followed by an optional else statement, which executes when all the condition becomes false.

nested if statements An if or elseif statement inside another if or elseif statement(s).

switch statement A switch statement allows a variable to be tested for equality against a list of values.

35

VBScript provides following types of decision making statements.

VBScript If Statement

Dim temperaturetemperature = 20If temperature > 25 Then

document.write("Wear a T-Shirt!")Else

document.write("Wear a long-sleeved shirt!")End If

36

VBScript ElseIf

The basic idea of the ElseIfstatement is to create an If Statement withinanother If Statement. This way you can check for many different cases in a single If Statement clause.

37

Dim temperaturetemperature = 65If temperature > 70 Then

document.write("Wear a T-Shirt!")ElseIf temperature > 60 Then

document.write("Wear a hat!")ElseIf temperature > 50 Then

document.write("Wear a long-sleeved shirt!")Else

document.write("Wear a coat!")End If

Switch Statements in VBScript

When a User want to execute a group of statements depending upon a value of an Expression, then Switch Case is used.

Each value is called a Case, and the variable being switched ON based on each case.

Case Else statement is executed if test expression doesn't match any of the Case specified by the user.

Case Else is an optional statement within Select Case, however, it is a good programming practice to always have a Case Else statement.

38

39

Dim MyVar

MyVar = 1

Select case MyVar

case 1

Document.write "The Number is the Least Composite Number"

case 2

Document.write "The Number is the only Even Prime Number"

case 3

Document.write "The Number is the Least Odd Prime Number"

case else

Document.write "Unknown Number"

End select

VBScript Loops

A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in VBScript.

40

41Loop Type Description

for loopExecutes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

for ..each loopThis is executed if there is at least one element in group and reiterated for each element in a group.

while..wend loop This tests the condition before executing the loop body.

do..while loops

The do..While statements will be executed as long as condition is True.(i.e.,) The Loop should be repeated till the condition is False.

do..until loops

The do..Until statements will be executed as long as condition is False.(i.e.,) The Loop should be repeated till the condition is True.

http://www.tutorialspoint.com/vbscript/vbscript_do_until_loop.htmhttp://www.tutorialspoint.com/vbscript/vbscript_do_until_loop.htm

Loop Control Statements42

Control Statement Description

Exit For statement

Terminates the For loop statement and transfers execution to the statement immediately following the loop

Exit Do statement

Terminates the Do While statement and transfers execution to the statement immediately following the loop

VBScript For Loops43

For counter = start To end [Step stepcount]

[statement 1]

[statement 2]

....

[statement n]

[Exit For]

[statement 11]

[statement 22]

....

[statement n]

Next

44

Here is the flow of control in a For Loop:

The For step is executed first. This step allows you to initialize any loop control variables and increment the step counter variable.

Secondly, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the For Loop.

After the body of the for loop executes, the flow of control jumps to the Next statement. This statement allows you to update any loop control variables. It is updated based on the step counter value.

The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the For Loop terminates.

45

Dim a : a=10

For i=0 to a Step 2 'i is the counter variable and it is incremented by 2

document.write("The value of i is : " & i)

document.write("")

Next

VBScript For...Each Loops46

For Each element In Group

[statement 1]

[statement 2]

....

[statement n]

[Exit For]

[statement 11]

[statement 22]

Next

'fruits is an array

fruits=Array("apple","orange","cherries")

Dim fruitnames

'iterating using For each loop.

For each x in fruits

fruitnames=fruitnames&x&vbnewline

Next

msgbox fruitnames

VBScript While...Wend Loop47

While condition(s)

[statements 1]

[statements 2]

...

[statements n]

Wend

48

Dim Counter : Counter = 10

While Counter < 15 ' Test value of Counter.

Counter = Counter + 1 ' Increment Counter.

document.write("The Current Value of the Counter is : " & Counter)

document.write("")

Wend ' While loop exits if Counter Value becomes 15.

VBScript Do..While statement49

Do

[statement 1]

[statement 2]

...

[statement n]

[Exit Do]

[statement 1]

[statement 2]

...

[statement n]

Loop While condition

50

i=10

Do

i = i + 1

Document.write("The value of i is : " & i)

Document.write("")

Loop While i

Do..Until Loops in VBScript51

Do Until condition

[statement 1]

[statement 2]

...

[statement n]

[Exit Do]

[statement 1]

[statement 2]

...

[statement n]

Loop

52

i=10

Do Until i>15 'Condition is False. Hence loop will be executed

i = i + 1

Document.write("The value of i is : " & i)

Document.write("")

Loop

VBScript Procedures

What is a Function? A function is a group of reusable code which can

be called anywhere in your program. This eliminates the need of writing same code over and over again. This will enable programmers to divide a big program into a number of small and manageable functions.

Apart from inbuilt Functions, VBScript allows us to write user-defined functions as well. This section will explain you how to write your own functions in VBScript.

53

Function Definition 54

Function Functionname(parameter-list)

statement 1

statement 2

statement 3

.......

statement n

End Function

Before we use a function, we need to define that particular function. The most common way to define a function in VBScript is by using the Function keyword, followed by a unique function name and it may or may not carry a list of parameters and a statement with a End Function keyword, which indicates the end of the function.

Calling a Function55

To invoke a function somewhere later in the script, you would simple need to write the name of that function with the Call keyword.

Function sayHello()

msgbox("Hello there")

End Function

Call sayHello()

Function Parameters56

Function sayHello(name, age)

msgbox( name & " is " & age & " years old.")

End Function

Call sayHello(Johnny", 13)

Returning a Value from a Function57

Function concatenate(first, last)

Dim full

full = first & last

concatenate = full 'Returning the result to the function name itself

End Function

' Here is the usage of returning value from function.

dim result

result = concatenate("Zara", "Ali")

msgbox(result)

Sub Procedures

Sub Procedures are similar to functions but there are few differences. Sub procedures DONOT Return a value while

functions may or may not return a value. Sub procedures Can be called without call

keyword. Sub procedures are always enclosed within Sub

and End Sub statements.

58

59

Sub sayHello()

msgbox("Hello there")

End Sub

sayHello()

VBScript Events VBScript's interaction with HTML is handled through

events that occur when the user or browser manipulates a page.

When the page loads, that is an event. When the user clicks a button, that click too is an event. Another example of events are like pressing any key, closing window, resizing window, etc.

Developers can use these events to execute VBScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated and virtually any other type of response imaginable to occur.

Events are a part of the Document Object Model (DOM) and every HTML element has a certain set of events, which can trigger VBScript Code.

60

onclick Event - example61

Function sayHello()

msgbox "Hello World"

End Function

onclick: triggered when the user clicks on the button onmouseover: triggered when the mouse pointer is placed

over the button onmouseout: triggered when the mouse pointer is moved

away from the button ondblclick: triggered when the user double-clicks on the

button onmousedown: triggered when the mouse button is

depressed onmouseup: triggered when the mouse button is released onmousemove: triggered when the mouse pointer is moved

whilst over the buttonAnd the beauty of these events is that each event has a

subroutine associated with it.

62

Onclick Subroutine

The obvious event for any button is the onclick event -but before the onclick event can be used the button needs to be defined using HTML:

Next the onclick subroutine is required - and the name of the subroutine always follows the same convention:

prefix - the id of the button separator - an underscore suffix - the name of the event

63

So, for example, the name for the subroutine, in this case, will be button1_onclick:

sub button1_onclick

msgbox(You clicked me)end sub

64

65

Function AlertMsg

Msgbox("ALERT !")

End Function

Function onmourse_over()

Msgbox("Onmouse Over")

End Function

Sub txt2_OnMouseOut()

Msgbox("Onmouse Out !!!")

End Sub

Sub btnButton_OnMouseOut()

Msgbox("onmouse out on Button !")

End Sub

Object Oriented VBScript VBScript runtime objects help us to accomplish various tasks. This

section will help you understand how to instantiate an object and work with it.

Syntax :Inorder to work with objects seamlessly, we need to declare the object and instantiate it using Set Keyword.

Dim objectname 'Declare the object nameSet objectname = CreateObject(object_type)

Example :In the below example, we are creating an object of type Scripting.Dictionary.

Dim objSet obj = CreateObject("Scripting.Dictionary")

66

Destroying the Objects

The significance of destroying the Object is to free the memory and reset the object variable.Syntax : Inorder to destroy the objects, we need to use Set Keyword

followed by the object name and point it to Nothing.Set objectname = Nothing 'Destroy the object.

Example :In the below example, we are creating an object of type Scripting.Dictionary.

Dim obj Set obj = CreateObject("Scripting.Dictionary")Set obj = Nothing

67

68

Object Description

Dictionary Stores a collection of key and data values

Drive Accesses information about a disk drive; part of FileSystemObject

Drives Stores a collection of Drive objects; part of FileSystemObject

Err Holds information about runtime errors

69

Simple Form

Name:

Name:

Set FormObject = document.form1

document.Form1

Refers to the form by name Form1

document.Form1.FirstName.value

Refers to the value typed into the textbox named FirstName by the client, in the form named Form1

VBScript and Forms

You can use Visual Basic Scripting to do much of the form processing that you'd usually have to do on a server. You can also do things that just can't be done on the server.The process to validate the forms are as under. The two things should be checked.

1. All of the required data is entered. 2. The data entered is valid or not.

70

71

Example - Simple ValidationSimple Validation

Simple Validation

Enter a value between 1 and 10:

72 Vb Script example

Option Explicit

Sub cmdSubmit_onClick

' Check whether user has entered the required text or not.

If(Len(document.myform.txtage.value)= 0) then

MsgBox "Please enter your age before submitting."

Exit Sub

End If

' Check the data entered is numeric or not.

If ( Not (IsNumeric(document.myform.txtage.value))) then

MsgBox "Please enter numeric data"

Exit Sub

End If

'Check the range of the age

If (document.myform.txtage.value 100) then

Msgbox "Age entered is Invalid."

Exit Sub

End If

'If all is fine submit the data

MsgBox "Thanks for providing your age."

Document.myform.submit

End sub

Please enter your age:

Example - Validating in the Button Event

Client-Side Scripting with VBScriptIntroductionVBScript: Client Side ScriptingVBScript: Why Learn and Use It?Do's & Don'tsVBScript InstallationVBScript First ScriptVBScript TagVBScript VariablesDeclaring VariablesDeclaring Variables in VBScriptAssigning Values to the VariablesExamplesScope of the VariablesScope of the Variables - DimSlide Number 16Scope of the Variables - PUBLICSlide Number 18Scope of the Variables - PRIVATESlide Number 20VBScript ConstantsDeclaring ConstantsSlide Number 23OperatorsOperatorsOperatorsOperatorsOperatorsOperatorsSlide Number 30VBScript ArraysSlide Number 32Slide Number 33VBScript - Decision MakingSlide Number 35VBScript If StatementVBScript ElseIfSwitch Statements in VBScriptSlide Number 39VBScript LoopsSlide Number 41Loop Control StatementsVBScript For LoopsSlide Number 44Slide Number 45VBScript For...Each LoopsVBScript While...Wend LoopSlide Number 48VBScript Do..While statementSlide Number 50Do..Until Loops in VBScriptSlide Number 52VBScript ProceduresFunction Definition Calling a FunctionFunction ParametersReturning a Value from a FunctionSub Procedures Slide Number 59VBScript Eventsonclick Event - exampleSlide Number 62Onclick SubroutineSlide Number 64Slide Number 65Object Oriented VBScriptDestroying the ObjectsSlide Number 68Slide Number 69VBScript and FormsSlide Number 71Slide Number 72