<<

1

Client-Side Scripting with VBScript 2 Introduction • Script (VBScript) – Subset of Visual Basic – IE contains VBScript scripting engine (interpreter) – Similar to JavaScript • JavaScript used more for client-side scripting – VBScript de facto language for ASP () 3 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 to develop web applications. 4 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. 5 Do's & Don'ts DO 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. 6 VBScript Installation • VBScript is a client side 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.

VBScript Supported Browsers • 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. 7 VBScript First Script 8 VBScript

12 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(#) 13 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# 14 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 15 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. 16 17 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. 18 19 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. 20 21 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. 22 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. 23

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 operators

VBScript operation Arithmetic Algebraic VBScript operator expression 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 p Exponentiation ^ q Q ^ p Negation - -e -e Modulus q r Mod q Mod r

26 Operators • Comparison operators Standard algebraic V BSc r i p t Example of Mea ning of VBScrip t equality operator or comparison V BSc r i p t ond ition relational operator operator 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 ≤ <= m <= s m is less than or equal to s

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 operators

Truth tables for VBScript Logical Operators Logical And: Logical Or: True And True = True True Or True = True True And False = False True Or False = True False And True = False False Or True = True False And False = False False Or False = False Logical Imp: Logical Eqv: True Imp True = True True Eqv True = True True Imp False = False True Eqv False = False False Imp True = True False Eqv True = False False Imp False = True False Eqv False = True Logical Xor: Logical Not: True Xor True = False Not True = False True Xor False = True Not False = True False Xor True = True False Xor False = False

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 30

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

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") 32

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. 33 34 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. 35 VBScript provides following types of decision making statements.

Statement Description An if statement consists of a boolean if statement expression followed by one or more statements.

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

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

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

A switch statement allows a variable to be switch statement tested for equality against a list of values. 36 VBScript If Statement 37 VBScript ElseIf The idea of 38 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. 39 40 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. 41 Loop Type Description

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

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

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

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

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

Control Statement Description Terminates the For loop statement and transfers execution Exit For statement to the statement immediately following the loop Terminates the Do While statement and transfers execution Exit Do statement to the statement immediately following the loop 43 VBScript For Loops

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 46 VBScript For...Each Loops For Each element In Group [statement 1] [statement 2] 47 VBScript While...Wend Loop

While condition(s) [statements 1] [statements 2] ... [statements n] Wend 48 49 VBScript Do..While statement

Do [statement 1] [statement 2] ... [statement n] [Exit Do] [statement 1] [statement 2] ... [statement n] Loop While condition 50 51 Do..Until Loops in VBScript

Do Until condition [statement 1] [statement 2] ... [statement n] [Exit Do] [statement 1] [statement 2] ... [statement n] Loop 52 53 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. 54 Function Definition

Before we use a function, we need 55 Calling a Function

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

57 Returning a Value from a Function

58 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. 59 60 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 . 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. 61 onclick Event - example

• onclick: triggered when the user clicks on the button 62 • 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 button And the beauty of these events is that each event has a associated with it. 63 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 64

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

65



66 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 name Set objectname = CreateObject(object_type) Example : In the below example, we are creating an object of type Scripting.Dictionary. Dim obj Set obj = CreateObject("Scripting.Dictionary") 67 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 68

Object Description

Stores a collection of key and data Dictionary values

Accesses information about a disk Drive drive; part of FileSystemObject

Stores a collection of Drive objects; Drives part of FileSystemObject

Holds information about runtime Err errors 69

Set FormObject = document.form1 Simple Form document.Form1 Refers to the form by name Form1

Name:
document.Form1.FirstName.value
Refers to the value typed into the textbox named FirstName by the client, in the form named Form1
Name:
70 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. 71 Example - Simple Validation Simple Validation

Simple Validation


Enter a value between 1 and 10:
72 Vb Script example
Please enter your age: