OUR MUST POPULAR POST

Friday, June 28, 2013

Session -1
           
Introduction
VBScript is a scripting language for HTML pages on the World Wide Web and corporate intranets. VBScript is a member of Microsoft's Visual Basic family of development products however VBScript mainly focuses for the Web Pages Programming and there are some differences between VBScript and Visual Basic.
A scripting language is a type of programming language used to provide control in another host environment. It is interpreted language which is interpreted by the compatible interpreter. In case of VBScript the interpreter is the web browser which will support the VBScript language such as Internet Explorer.
Learning VBScript
VBScript is much easier to learn than programming languages such as Java, C/C++, and other scripting languages such as JavaScript. Derived from the BASIC language, VBScript should not be difficult for anyone who has any computer programming experience.
To start working with VBScript, you need several things: a browser that supports VBScript, the VBScript runtime interpreter, access to required controls, and an editor or other tool to help you assemble Web pages or edit HTML documents. The first step is to obtain a browser that includes VBScript runtime support if you do not already have one. Microsoft's Internet Explorer 3.0 was the first publicly available browser that supported VBScript. Any browser that supports VBScript includes the VBScript runtime interpreter. Therefore, if you install the browser, you have everything you need to run VBScript, including the runtime interpreter. You don't need to obtain any other pieces
Ability of VBScript
VBScript lets the user interact with a Web page rather than simply view it. Many scenarios are possible for this interaction. For instance, Web pages can ask questions and respond to the user's answers. A VBScript can then take input from the user and check the data to make sure it is valid or meets some criteria. Then it can put an Internet server to work by actually storing the data or causing some action to take place on the server based on the user's input. For example
VBScript could respond to a user's request for an airline reservation by reading in the data, checking to make sure that the request is complete and that the phone number and ZIP code are in a valid format, informing the user of the estimated price, and then notifying the server of the reservation. All these tasks could be performed by the code in the Web page that was downloaded across the Internet as it sits on the user's client PC. The server, in turn, makes sure that the ticket is available, books the flight, and arranges to deliver the tickets to the customer.
VBScript can play an important role in validating data, costing, providing impressive multimedia feedback, and initiating data storage. VBScript can also perform calculations on data, such as computing the cost of an item that includes the sales tax. Another important aspect of this programming model is that you can also use intrinsic HTML form controls and Microsoft's ActiveX controls with VBScript to give Web pages an attractive look and feel. Intrinsic HTML form controls give the Web page developer a standard set of controls similar to those used in the Windows environment.


VBScript Enhances Browsers and HTML
VBScript enhances Web browsers in a variety of helpful and significant ways. Web browsers are able to read and interpret HTML code, formatting the text and other data in a Web page based on the specifications of the browser.
Web pages built entirely on HTML often require the user to set a series of controls, such as check boxes and text fields. Typically an entire form's worth of data is supplied at a time. After filling in fields on a form, the user can click on a button, usually called Submit, and the contents of the Web page are sent back to the server. The only work that the client's computer performs is to display the Web page to the user. The server performs all the intelligent work and processing. Remote processing not only increases the amount of traffic required on the Internet but also prevents the user from interacting with the Web page.
With VBScript, however, the Web page has its own intelligence. VBScript can, for example, make sure that what a user enters is valid before the user "submits" it to the server. Local validation eliminates a great deal of extra traffic, not to mention the delay the user must experience in waiting for the information to get to the server. One immediate benefit for the user is that faster, more responsive Web pages make the overall Web page experience more enjoyable.

Scripting(Script Tag in HTML)

Scripting allows you to take control of content in an HTML document. Like any other tag in HTML, the <SCRIPT> tag uses attributes and allows you to define a scripting language to control the objects in your document.
The LANGUAGE= attribute sets the scripting language in the <SCRIPT> tag. For VBScript, the language tag is "VBScript". The VBScript code itself is closed with the </SCRIPT> tag. To keep browsers that cannot use the code from displaying the code in a page, comment tags should surround the code:
<SCRIPT LANGUAGE="VBScript">
<!--
     SUB Button1_OnClick()
      MsgBox "Welcome to CSE.", 0, "Welcome Message"
     END SUB
-->
</SCRIPT>
When the HTML document is loaded into the browser, the browser sees the <SCRIPT> tag, and the code is sent to the interpreter. VBScript then compiles the code and runs the program.

Creating a Test Page

Many new programmers learn how to program by writing small programs that run from the command line. In HTML, there is no command line, so we'll set up a skeleton page that we can use to test some of the concepts and functions covered in this book. We'll call the skeleton program tester.htm.
<HTML>
<HEAD>
<TITLE>Tester Page</TITLE>
</HEAD>
<BODY>
<H1>Tester Page for VBS</H1>
<HR COLOR="BLUE">
<INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Click to test the code">
<SCRIPT LANGUAGE="VBS">
<!--
Sub Btn1_OnClick()
End Sub
-->
</SCRIPT>
</BODY></HTML>
In most VBScript programs, you'll need to attach the initialization of a program to some sort of action. In the tester.htm page, use the button click event to trigger the action that takes place. To be able to see what happens, we need to change the property of a control on the page, or we can use a message box. Once we have the skeleton program in place, we can test code in the browser.
To start, we'll create a Hello World program. Hello World is a traditional program created in various forms to test input and output techniques. The first Hello World program is fairly simple. To create the script, the following code is added to the Btn1_OnClick event in tester.htm:
Sub Btn1_OnClick
Dim Message
Message="Hello World!"
MsgBox Message, 0,"Tester Result"
End Sub
To test the new code, save tester.htm and then open it in Internet Explorer .
Comments in VBScript
is used to denote the Single Line Comment in VBScript.
Eg :      ‘ This is a comment.





Session-2

Variable

When users interact with computers, they usually get to some point where the computer asks them for information. A variable is a virtual container in the computer's memory that's used to hold information.
VBScript is very flexible about the type of information you can store. What's even better, the language is "smart" enough to let you store in the variable almost anything you want without telling it the kind of information ahead of time. There are, of course, limits to what and how much you can store, but VBScript is capable of letting you store a variety of types of information. When you create a variable in VBScript, you can assign to it numbers with or without decimal points, text, dates and times, and even objects such as ActiveX controls.

Creating  Variable

There are two types of variable based on variable creation.
Explicit Variable : The variables must be declared or created before they are used.
            Syntax : dim Variable_Name
            Eg. Dim myname
Implicit Variable : The variables are used without declaration.
            Eg. : myname =”Ram Shrestha”

Data Types

As mentioned, a variable is a name that represents the contents of some space in memory. Thinking of a variable in terms of memory space will help you to understand an important concept in programming: data types.
All variables in VBScript are of the type variant. A variant is a variable that is simply the name for a piece of data. The variant type doesn't differentiate between types of data until the time comes to process that data. This means that a variable can represent literally any value or type of value.

Subtypes of Variant Types

The variant type has a number of subtypes. Let's go through each of the subtypes and discuss how a variable of any given subtype will take up space in memory.

Boolean

One of the most basic data types in programming is the Boolean data type. This subtype in VBScript can have a value of either true or false. The Boolean type takes up very little space in memory.

Byte

The byte subtype can be a whole, positive number in the range of 0 to 255. Like the Boolean subtype, the byte subtype takes up very little space in memory.

Integer

The integer subtype takes up 2 bytes in memory and can be an integer value in the range of -32,768 to 32,767. An extra byte of storage makes a big difference in the value that a variable can hold.

Long

The long variable subtype is 4 bytes in size and can be a whole number in the range of -2,147,483,648 to 2,147,483,647.

Single

The single subtype contains a single-precision, floating-point number. Precision refers to the number of bytes of fractional value storage allotted to the variable. A single-precision number allots 2 bytes for fractional value storage. It takes 4 bytes to store a variable of the subtype single. The range of values that a single can hold is -3.402823E38 to -1.401298E-45 for negative values and 1.401298E-45 to 3.402823E38 for positive values.

Double

The double subtype takes up 8 bytes of storage, 4 bytes of which are reserved for a fractional value. The double subtype is extremely precise and is usually reserved for advanced mathematical and scientific operations. It has a range of -1.79769313486232E308 to -4.94065645841247E-324 for negative values and 4.94065645841247E-324 to 1.7976931348632E308 for positive values.

String

The string subtype is a group of up to approximately 2 billion characters. The size of the string variable depends on the length of the string.

Date

The date subtype is a number that represents a date in the range of January 1, 100 to December 31, 9999.

Empty

The empty subtype is returned for variants that aren't initialized. If the variable is a number, the value is 0. If it's a string, the value is "".

Object

The object subtype contains the name of an OLE Automation object. The object can then be manipulated using the variable.

Error

The error subtype contains an error number. You can use the generated error number to generate an expanded explanation of the error.

Scope

The scope of a variable refers to where in the script the variable is available for processing. A variable declared inside a procedure is limited in scope to that procedure. If a variable is declared outside of the procedures in the script, it is available to all the procedures in the script.
<HTML>
<HEAD>
<TITLE>VBS Variable Scope</TITLE>
</HEAD>
<BODY>
<H1>Tester Page for VBS</H1>
<HR COLOR="BLUE">
<INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Local Variable">
<INPUT TYPE="SUBMIT" NAME="Btn2" VALUE="Script Wide Variable">
<INPUT TYPE="SUBMIT" NAME="BTN3" VALUE="Out of Scope">
<SCRIPT LANGUAGE="VBScript”>
Option Explicit
Dim MyGlobal
MyGlobal="Access Ok"
Sub Btn1_OnClick()
Dim MyLocal
MyLocal="Local access Ok!"
MsgBox MyLocal,0,"Btn1 Clicked"
End Sub
Sub Btn2_OnClick
MsgBox MyGlobal,0,"Btn2 Clicked"
End Sub
Sub Btn3_OnClick
MsgBox MyLocal,0,"Btn3 Clicked"
End Sub
-->
</SCRIPT>
</BODY>
</HTML>
The page will display like :
If you run the code, you'll see that you can access the local variable by clicking Btn1. If you click Btn2, you'll access the variable that we declared globally. Finally, if you click Btn3, you'll get an error (display nothing) because the Btn3_OnClick procedure tries to access the variable declared in the Btn1_OnClick procedure.

Constants

A constant is a named value that doesn't change throughout a script. For example, the value of PI is 3.14. To use this constant in a script, you simply declare it, assign it, and use it like a variable.
 
Dim vbPi
 
vbPi = 3.14
 
Once you set the value of the constant, you can use it in your script as if it were the actual number. Keep in mind though that constants in VBScript are essentially just variables that you don't change in your program. Unlike other languages that allow you to set the value of a constant to static, there's no way to make a variable in VBScript unchangeable.

Arrays

Arrays allow you to group related sets of data together. When you create an array, you must specify its number of dimensions. VBScript allows you to create arrays with up to 60 dimensions. A one-dimensional array is like a column of tabular data; a two-dimensional array is like a spreadsheet with rows and columns; and a three-dimensional array is like a 3D grid that takes time and space into account.
You could create a one-dimensional array from a single column of tabular data. If there were 20 data points in the column, you could declare the array as follows:
 
Dim myArray(19)



 
Note
Arrays always begin at 0 and end at the number of data points in the array minus 1. Therefore, an array with 20 data points is initialized as Array_Name(19).



Operators

Arithmetic Operators

You perform calculations in VBScript in much the same way as you write out calculations longhand. The only difference is that you usually assign the result to a variable.
To add numbers, use the + operator, as shown in these two examples:
Result = 1 + 5
Result = ValueA + ValueB
To subtract numbers, use the - operator, as these two examples show:
Result = 5 - 1
Result = ValueB - ValueA
To multiply numbers, use the * operator; here are two examples of how to do that:
Result = 2 * 4
Result = ValueA * ValueB
To divide numbers, use the / or \ operator, as shown in the following examples:
Result = 2 / 4
Result = ValueA / ValueB
In division, you often have a remainder. Since you might want to perform calculations based on the remainder, you need a way to determine it. In VBScript, you do this by using the Mod function. For the following expression, the value of the result is set to 1:
Result = 7 Mod 2
To multiply by an exponent, use the ^ operator. This example is the same as 3 * 3 * 3 * 3:
                    Result = 3 ^ 4
You can also use this example, which is the same as ValueC * ValueC:
Result = ValueC ^ 2
You can negate a value by using the - operator, as shown in these two examples:
Result = -2 * 3
Result = -ValueA * ValueB
When you mix operators, VBScript performs calculations using the same precedence order your math teacher taught you. For example, multiplication and division in equations are carried out before subtraction and addition, as shown in these examples:
3 + 2 * 6 = 15

2 / 2 + 3 = 4
The complete precedence order of operators is shown in Table. According to the table, exponents have the highest precedence order and are always calculated first.
Table showing The precedence order of arithmetic operations.

Order
Operation
1
Exponents (^)
2
Negation (-)
3
Multiplication (*) and Division (/)
4
Remainders (Mod)
5
Addition (+) and Subtraction (-)

Example : 1

<HTML>
<HEAD>
<TITLE>Addition Operator Example</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
SUB AddValues_OnClick()
  Dim UserValue1 
  Dim UserValue2
  Dim Sum
  UserValue1=InputValue1.Value
  UserValue2=InputValue2.Value
' Find out if the values are numeric; if they are, convert
' them to numeric values so that the operator will add them.
  If IsNumeric(UserValue1) and IsNumeric(UserValue2) Then
     Sum = CDbl(UserValue1) + CDbl(UserValue2)
    MsgBox "The Sum of " & UserValue1 & " + " & UserValue2 & " = " & Sum
  Else
' If the values are not both numeric, concatentate the values
' using the addition operator.
    Sum = UserValue1 + UserValue2
    MsgBox "The Sum of " & UserValue1 & " + " & UserValue2 & " = " & Sum
  End If
END SUB
-->
</SCRIPT>
</HEAD>
<BODY>
<CENTER>
<FONT SIZE=6>Addition Operator<P>
</CENTER>
<HR>
<FONT SIZE=4>
<PRE> Type the first value: <INPUT NAME=InputValue1 SIZE=20>
Type the second value: <INPUT NAME=InputValue2 SIZE=20>
<HR>
<CENTER>
<INPUT TYPE=BUTTON VALUE="Add the values" NAME="AddValues">
</CENTER>
</FONT>
</BODY>
</HTML>

Example : 2
<HTML>
<HEAD>
<TITLE>Multiply Operator Example</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
SUB MultiplyVal_OnClick()
  Dim UserVal1 
  Dim UserVal2
  Dim Result
  UserVal1=InputValue1.Value
  UserVal2=InputValue2.Value
 If IsNumeric(UserVal1) and IsNumeric(UserVal2) Then
    Result = UserVal1 * UserVal2
    MsgBox "The Result of " & UserVal1 & " * " & UserVal2 & " = " & Result
  Else
     MsgBox "One of the values is not numeric."
  End If
END SUB
-->
</SCRIPT>
</HEAD>
<BODY>
<CENTER>
<FONT SIZE=6>Multiplication Operator<P>
</CENTER>
<HR>
<FONT SIZE=4>
<PRE> Type the first value: <INPUT NAME=InputValue1 SIZE=20>
Type the second value: <INPUT NAME=InputValue2 SIZE=20>
<HR>
<CENTER>
<INPUT TYPE=BUTTON VALUE="Multiply values" NAME="MultiplyVal">
</CENTER>
</FONT>
</BODY>
</HTML>

Comparison Operators

Comparison operators are used to compare one or more variables, numbers, constants, or a combination of the three. VBScript has many different types of comparison operators, and each type checks for a different comparison condition.
Operator
Purpose
=
Equality
<> 
Inequality
> 
Greater Than
< 
Less Than
>=
Greater Than or Equal To
<=
Less Than or Equal To

Equality (=)

You use the equality operator to see if a variable, constant, or number is equal to another. It's common to mistake the equality operator for the assignment operator, which is also represented by an equals sign. You use the assignment operator to set a variable equal to another variable, number, string, constant, or other data entity. For example, the statement
a = b
assigns the value contained in b to the variable a.
The equality operator, on the other hand, is used to test whether one value is equal to another. The syntax for the equality operator looks similar to that for the assignment operator  however Equality is always used in the context of checking a condition. For example, a statement such as
if a = b then
is an example of the equality operator because it is a conditional check.
 

Logical Operators

The last category of operators in VBScript is logical operators. The logical operators are probably the most difficult operators to understand.

Negation (Not)

The first operator is called the negation operator. This operator has the following syntax:
result = Not expression

Conjunction (And)

The conjunction operator compares two or more variables in some type of test. The syntax for the conjunction operator is
result = expression1 And expression2
 

In order to obtain True in the result variable, both expression1 and expression2 must be true.

Disjunction (Or)

Another frequently used logical operator is the disjunction operator. This operator has the same syntax as the conjunction operator:
result = expression1 Or expression2
 
This operator behaves quite a bit differently from the conjunction operator. In this case, any of the expressions can be true for the result to be true. The result is false only if all the expressions are false. 
 

String Concatenation

One special operator does not fit in any of the other classes. This operator, called the string concatenation operator, is represented by the & symbol.
First_Name = "Buddy"
and the second holds the string
Last_Name = "Bird"
 
to form a complete name, you need to concatenate these two strings. The syntax for the concatenation operator is
result = string1 & string2 
 
Examples using operators
 
<HTML>
 
<TITLE>T-Shirt Shop</TITLE> 
 
<H1>T-Shirt Order Form</H1>
 
<BODY>
 
<HR>
 
<CENTER>
<PRE>    Red Shirts     <INPUT NAME="txtRed" SIZE=5></PRE>
<PRE>    Green Shirts   <INPUT NAME="txtGreen" SIZE=5></PRE>
<PRE>    Blue Shirts    <INPUT NAME="txtBlue" SIZE=5></PRE>
</CENTER> 
 
<CENTER>
<INPUT TYPE=BUTTON VALUE="Order!" NAME="cmdOrder">
<INPUT TYPE=BUTTON VALUE="Cost!" NAME="cmdCost">
</CENTER> 
 
 
<SCRIPT LANGUAGE="VBScript">
<!--  Option Explicit
 
                         Dim Quantity_Ordered
    Dim Quantity_Charged
 
                         Dim Red
                         Dim Green
                         Dim Blue
    Dim Cost
    Dim Tax
 
    
   Sub cmdOrder_OnClick()
    if txtRed.value="" then
                         Red=0
    else
                                             Red = CInt(txtRed.Value)
                         end if
 
    if txtGreen.value="" then
                         Green=0
    else
                         Green = CInt(txtGreen.Value) 
    end if
 
    if txtBlue.value="" then
                         Blue=0
    else
                        Blue = CInt(txtBlue.Value) 
    end if
      
    Quantity_Ordered = Red + Green + Blue
                         Quantity_Charged = Quantity_Ordered - 1
                         MsgBox "You have submitted a request to order " & _
        Quantity_Ordered & " shirts! and You will be charged for " & _
    Quantity_Charged & " shirts,because you get one shirt for free!"
 
   End Sub
 
   Sub cmdCost_OnClick()
 
    if txtRed.value="" then
                         Red=0
    else
                                             Red = CInt(txtRed.Value)
                         end if
 
    if txtGreen.value="" then
                         Green=0
    else
                         Green = CInt(txtGreen.Value) 
    end if
 
    if txtBlue.value="" then
                         Blue=0
    else
                        Blue = CInt(txtBlue.Value) 
    end if
  
    
   Quantity_Ordered = Red + Green + Blue
   Quantity_Charged = Quantity_Ordered - 1
 
   Cost = Quantity_Charged * 20
 
   Tax = Cost * 0.06
 
   Cost = Cost + Tax
 
  
MsgBox "The cost for the Total shirts is Rs." & Cost & "."
 
End Sub
 
-->
</SCRIPT>
 
</BODY>
 
</HTML> 
 
 
The Page look likes as below
 
 
 
 


Session -3                                                  Decision Making Statements
Decision-making in programs is how you control the flow of code execution in the program. Keep in mind that computers aren't really that good at thinking things through. You have to tell the program what to do every step of the way.
Fortunately, VBScript gives you a variety of ways to direct the flow of your code. The mechanisms used to accomplish this in VBScript are called control structures. They are called structures because you construct your code around them.

If...Then...Else

The If...Then...Else statement is one of the basic capabilities of a computer language. This statement tests for the truth of a statement and, depending on the answer, processes information or moves on to another piece of code.
Example : If...Then...Else in a VBS script.
<HTML>
<HEAD>
<TITLE>Tester Page</TITLE>
</HEAD>
<BODY>
<H1>If Tester Page for VBScript</H1>
<HR COLOR="BLUE">
<CENTER>
<FONT COLOR=RED SIZE=5>Question:</FONT><BR>
<FONT COLOR=BLUE SIZE=6>What is the Capital of Japan?</FONT><BR>
<br>
<INPUT TYPE="TEXT" NAME="Txt1" size=20>
<br><br>
<INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Click To Test Your Answer">
</CENTER>
<SCRIPT LANGUAGE="VBSCRIPT">
<!--
Sub Btn1_OnClick()
Dim Message
If Txt1.Value = "Tokyo" or txt1.value="tokyo" 
                    or t1.value="TOKYO" then 
                                         Message="You're right!"
Else
                                         Message="You are Wrong Try again"
End If
MsgBox Message, 0,"Tester Result"
End Sub
-->
</SCRIPT>
</BODY></HTML>
 
When Btn1 is clicked, the If...Then...Else statement asks if the value of the Txt1 text input box is Tokyo. If the answer to that question is true, the program sets the value of the variable Message to “You're right”. If the answer is false, the value of Message is set to “You are Wrong Try again”.
You can do as many tests as you want by simply placing more ElseIf statements between the first If statement and the End If statement. The syntax of such a structure looks like this:
If condition1 = True Then
   ...the code that executes for condition1
ElseIf condition2 = True Then
   ...the code that executes for condition2
ElseIf condition3 = True Then
   ...the code that executes for condition3
End If
Example :
<html>
<body>
<h2><center>Roller Skating Club</center></h2>
<table border=0 width=60% align=center>
<caption>Entry Form</caption>
<tr>
<td>Input Your Name :</td><td> <input type="text" name ="txtname" size="30"></td>
</tr>
<tr>
<td>Input Your Age :</td><td><input type="text" name="txtAge" size="2"></td>
</tr>
<tr>
<td rowspan=2><center>
<input type="button" name="cmdTest" Value="Test">
</center></td>
</tr>
</table>
<SCRIPT LANGUAGE="VBScript">
<!--  Option Explicit
   Sub cmdTest_OnClick()
                If txtname.value="" or txtage.value="" then
                MsgBox "Name and Age can not be blank"
                Else
                                Dim Age
                                Age = CInt(txtAge.Value)
                                                If Age <14 Then
                                                                MsgBox "You are too young for the game"
                                                ElseIf Age >=14 and age<=30 Then
                                                                MsgBox "Welcome to the Action Game"
                                                ElseIf Age >30  and Age < 45 Then
                                                                MsgBox "You can take part in game with support"
                                                ElseIf Age >=45 and age<=55 Then
                                                MsgBox "You can just watch the game"
                                                Else
                                                MsgBox "You are not allowed to entry"
                                                End If
                End If
   End Sub
-->
</SCRIPT>
</html>


Select Case

In the previous section, you saw how to use the If…Then and If…Then…Else conditional structures. You saw an example in which five tests were made within this structure. In this case and cases where you have to perform a large number of tests on the same expression, you can  use the Select statement. The Select statement often makes your code easier to read and interpret than would a long list of Else and Else If statements. The Select Case structure is defined as follows:
Select Case test_expression
    Case expression-1
       ...this is the code that executes if expression-1 matches test_expression
    Case expression-2
       ...this is the code that executes if expression-2 matches test_expression
    Case expression-3
       ...this is the code that executes if expression-3 matches test_expression
    .
    .
    .
    Case Else n
       ...this is the code that executes if expression-n matches test_expression
End Select
Example :
<HTML>
<HEAD>
<TITLE>Select Case Sample</TITLE>
</HEAD>
<BODY>
<H1>
<EM>Using the Select Case Structure</EM>
</h1>
<HR>
<P>Enter your Zone Id and click the 'Check' button.
<br>VBScript will determine Your Zone.
<pre>
Zone Id     <INPUT NAME="txtZoneId" SIZE=5 >
<br><br>
  <INPUT TYPE="BUTTON" VALUE="Check" NAME="cmdCheck">
</pre>
<HR>
<center>
<em>College of Softwarte Engineering</em><BR>
</center>
<SCRIPT LANGUAGE="VBScript">
<!--  Option Explicit
   Sub cmdCheck_OnClick()
      Dim ZoneId
      Dim ZoneName
      if Not IsNumeric(txtZoneId.Value) then
         msgbox "You must supply a Numeric Value!",0,"No Numeric Value"
         exit sub
      end if
      ZoneId = CInt(txtZoneId.Value)
      Select Case ZoneId
         Case 1
            Zonename="Mechi"
         Case 2
            Zonename="Koshi"
         Case 3
            Zonename="Sagarmatha"
         Case 4
            Zonename="Janakpur"
         Case 5
            Zonename="Bagmati"
         Case 6
            Zonename="Narayani"
         Case 7
            Zonename="Gandaki"
         Case 8
            Zonename="Dhaulagiri"
         Case 9
            Zonename="Karnali"
         Case 10
            Zonename="Rapti"
         Case 11
            Zonename="Lumbini"
         Case 12
            Zonename="Seti"
         Case 13
            Zonename="Bheri"
         Case 14
            Zonename="Mahakali"
         Case Else
            ZomeName="Invalid Zone Id"
      End Select
      MsgBox "The Zone you live in is " & ZoneName
   End Sub
-->
</SCRIPT>
</BODY>
</HTML>



Using Control Structures to Make Code Repeat

On occasion, you will need to write code that repeats some set of statements. Oftentimes, this will occur when you need to perform some calculation over and over or when you have to apply the same calculations or processing to more than one variable, such as changing the values in an array.

For...Next

The For...Next statement is used to run a block of code statements a certain number of times. The syntax for this structure is
For counter = start to finish
   ...code that gets repeated
Next
where counter is a variable used for counting purposes that begins at the number specified by the start variable and counts up by one, each time executing the code within the structure, until it reaches finish. Usually, counter is incremented by one each time through the loop, although you can change the value of the increment
Example :
<html>
<input type="button" value="Click Here" name="btn1">
<script language="vbscript">
<!--
sub btn1_OnClick()
 
    Dim x
 
    For x = 1 to 10
 
    msgbox x,vbOkOnly+vbInformation,"For Loop"
 
    Next
 
End Sub
-->
</script>
In this example, the counter starts at 1 and repeats till itts value reaches to 10. The vbokonly + vbInformation denotes the message box has OK button only with Information(“i”) icon.
 
You can also steps at certain interval by using Step keyword in For Loop.eg.
 
For x = 5 To 50 Step 5
Msgbox x
If x > 20 Then Exit For
Next
In this case, the counter starts at 5 and stops at 50 for a total of 10 iterations. The loop is exited after five iterations, because x is greater than 20.
You could also use the Step value to count down, using negative numbers. Starting with a higher number and counting down to a lower one would look something like this:
Dim x
For x = 10 to 1 Step -1
msgbox x
Next
Example : 2
Suppose you have an array called Salaries that contains 30 elements, and you want to set all these elements to a value of 30,000. One way to do this is to enter the code
Salaries(0) = 30000
Salaries(1) = 30000
Salaries(2) = 30000
.
.
.
Salaries(29) = 30000
If you did it this way, you would have to enter thirty lines of code. However, you have a much easier way. In this case, you're repeating the same operation thirty times, but each time, you're assigning the value to a different element in the array. Instead, try entering the following code:
For i = 0 to 29
   Salaries(i) = 30000
Next
You've reduced the code to three lines.
Exiting a For Loop
If you ever want to break out of a loop, such as when an error occurs, you can use the Exit For statement. Usually, you break out of a loop because of a problem or some exception.
Eg.
For I = 1 to 10
   Response = MsgBox("Would you like to continue adding
             the salaries?")
   If Response = 6 Then                         ‘ user clicks Yes
       Result = Result + Salaries(I)
   Else
       Exit For
   End If
Next

For Each...Next

The For Each...Next loop is used like the For...Next loop. It is used to test conditions in collections of objects. Objects have properties that are specified by keywords that are appended to the object name after a period. If I had an object with the property of color, you could access that property with MyObject.Color. Groups of objects are called collections, and you can test each of the objects for the truth of a statement using For Each...Next:
For Each Car in Lot
     if Car.Color = "Red" then
     MsgBox "Red car!", 0, "Answer"
     End If
Next
In this example, the collection of objects is called Lot, and the objects are of the type Car. We go through the cars in the lot, and when we get to a red one we see a message.

Do...Loop

Another common looping statement is Do...Loop. A Do...Loop statement is usually better to use than a For...Next and Exit For combination. The Do...Loop statement allows you to create a loop that runs an infinite number of times. You need to be careful when using this statement-you don't want to accidentally get your script into a loop that it can't get out of:
Dim x
x=1
Do Until x = 25
x = x + 1
Loop
In this example, the place where you need to be careful is in Do Until x = 25. If the initial value of x was 30, the code would loop continuously without the x = 25 value ever being met.
There are two ways to test for a true value in the Do...Loop statement. You can use the Until keyword to repeat the loop until a condition is true or the While keyword to repeat while the condition is true:
Dim x
x = 10
Do While x < 100
x = x + 10
Loop
By placing the While or Until keyword after the Loop statement, you can make sure that the code inside the loop is run at least once:
Dim x
x = 1
Do
x = x + 1
If x > 30 Then Exit Loop
Loop Until x = 30
The code in this Do...Loop block is run at least once before it's ended. We've also added a safety feature in the form of an Exit Loop command that's issued if x is found to be greater than 30. If x is greater than 30, there is no chance that the value will ever be 30.

While...Wend

According to Microsoft, While...Wend is included in VBScript for those programmers who are familiar with its usage, but it's not well documented. Microsoft recommends using Do...Loop instead, but let's take a quick look at the While...Wend statement to become familiar with its usage:
Dim x
x = 1
While x < 10
x = x + 1
Wend
The While...Wend statement repeats until the value of the While portion of the statement is true.


Session – 4                                                                              VBScript Function I
VBScript, like most other languages, stores code in procedures. Procedures are the building blocks of VBScript.
A procedure is a grouping of code statements that can be called by an associated name to accomplish a specific task or purpose in a program. Once a procedure is defined, it can be called from different locations in the program as needed.
Procedures come in two varieties: subroutines and functions.
The first type of procedure is the subroutine. A subroutine is a container that holds a series of VBScript statements. Suppose you'd like to create a block of code that accomplishes some specific task. Maybe you need to accomplish that task in various places throughout your code. All you need to do is create, or declare, the subroutine in your script. Once you've declared the subroutine, you can call it anywhere within your code. When your program calls a subroutine, the flow of the code is temporarily diverted to the statements within the subroutine. Once the subroutine has finished executing, control returns to the code that called the subroutine and execution picks up from there.
A subroutine is a block of code that can be called from anywhere in a program to accomplish a specific task. Subroutines can accept starting data through subroutine declaration variables called parameters. However, subroutines do not automatically return a result code or an argument to the caller.
The structure of a subroutine is
Sub Subroutine_Name(argument1, argument2, ..., argumentn)

   ...code within the subroutine

End Sub
where Subroutine_Name is the name of the subroutine and argument1 through argumentn are optional arguments, often called parameters, that you can pass to the subroutine. If you choose not to pass any arguments to the subroutine, the parentheses are optional, as you will see in a moment.
Example :



Sub ShowMessage(CurrentMessage) 

   MsgBox CurrentMessage, vbOkOnly, "Important Message"

End Sub
In this case, CurrentMessage is the argument, and it is treated like any other variable in the subroutine. The CurrentMessage argument variable starts out pre-initialized with a value that was supplied by the code that called this subroutine.
Frequently, a subroutine might not require any arguments, and you can drop the parentheses. For example, if you have a subroutine that simply displays information to the user, it doesn't need any arguments, as in the following code:
Sub ShowAboutMessage
   MsgBox "This Web page was designed by the WebWizard."

End Sub

Calling a Subroutine

A subroutine can be called  throughout the rest of the application it is declared and created . You can call subroutines by using the Call keyword or just entering the name of the subroutine on a line of code. For example, to call a subroutine called ShowMessage, we could enter
ShowMessage "This is the message."
we could also use the Call keyword and enter
Call ShowMessage("This is the message.")
Notice that in the first method, you do not place parentheses around the arguments of the subroutine. On the other hand, if you use Call, you must enclose the arguments in parentheses. This is simply a convention that VBScript requires. What if a subroutine has no arguments? To call the subroutine ShowAboutMessage, you could enter
ShowAboutMessage
or
Call ShowAboutMessage()
or we could use
Call ShowAboutMessage

Exiting a Subroutine

The code within your subroutine will execute until one of two things happens. First, the subroutine might get down to the last line, the End Sub line, which terminates the subroutine and passes the baton back to the caller. This statement can appear only once at the end of the subroutine declaration. The second possibility is that VBScript could execute the following code statement:
Exit Sub
when placed inside the subroutine. You might use this statement if you need to provide more than one exit point for the subroutine. However, you shouldn't need to use this very often if your subroutine is constructed properly. Consider the following subroutine:
Sub ConvertFeetToInches
   Feet = InputBox("How many feet are there?")
   If Feet < 0 Then
      Exit Sub
   Else
      MsgBox "This equals " & Feet * 12 & " inches."
   End If
End Sub

Functions

The second type of procedure is called a function. Like a subroutine, a function also holds a series of VBScript statements. The only difference is that a function actually returns a value to the code statement that called it.

Creating and Calling Functions

To declare a function, use the Function keyword instead of the Sub keyword. You end functions using the End Function statement. The structure of a function is
Function Function_Name(argument1, argument2, ..., argumentn)

     ...code within the function

End Sub
where Function_Name is the name of the function and argument1 through argumentn are optional arguments you can pass to the function. As with the subroutine, the parentheses are not required if no arguments are passed to the function.
Now that you've seen how to declare a function, you need to know how to call it. The benefit of using a function is that you can pass back a piece of data to the caller. The subroutine does not enable you to do this because it does not return anything. You will see a way to change variables in the calling code with a subroutine later in the chapter, but the function is a better way to transfer data back and forth. To call a function, you simply use the following syntax:
return_variable = function_name(argument1, argument2, ..., argumentn)
Notice that the syntax for a function is quite a bit different from the syntax for a subroutine. Here, you can assign the function to a variable
For example, if you create a function that converts meter to feets, you might name the function ConvertMeter:
Function ConvertMeter(Meter)
 
    Feet = Meter * 3.3
 
End Function
The function returns the value of  feet to the calling procedure.
To call the ConvertMeter function from another procedure, you must use a variable of some sort to hold the return value.
Feet = ConvertMeter(22)
Function procedures are great tools for working with data in a VBS script. When you create functions that you know you might want to use again, be sure to save them, so that you can easily reuse them in new scripts.
The following function requires three arguments-hours, minutes, and seconds-and returns the number of seconds:
Function GetSeconds(Hrs, Min, Sec)

   GetSeconds = Hrs * 3600 + Min * 60 + Sec

End Function

You could then call this function using a statement like
                    NumSeconds = GetSeconds(2, 34, 25)
where the total number of seconds is returned to the variable NumSeconds.

Basic Built-in Functions in VBScript

The message box is one of the most useful functions in VBScript. The two types of message boxes available in VBScript are the message box and the input box.

InputBox

The InputBox function makes it possible for you to get input from a user without placing a text control on the form.It takes seven possible parameters:
Syntax :
                    InputBox(prompt, title, default, xpos, ypos, helpfile, context)
All the arguments of the InputBox function are optional except prompt. Let's take a look at each of these parameters in detail.

prompt

The prompt argument is a string containing the question that you are asking your user:
InputBox("Enter the Answer Here")

Title

The Title argument determines the title of the dialog. This argument must be a string expression. If the title isn't specified, the title of the dialog defaults to the application name.
    InputBox("Enter the Answer Here","Answer")

default

The default argument specifies a string that appears in the input box on the dialog when the dialog is displayed. Leave this parameter blank if you don't want the dialog to display default text.
InputBox("Enter the Answer Here","Answer","Your Answer Here")

xpos and ypos

The xpos and ypos arguments specify where in relation to the screen the dialog is displayed. These arguments are made in twips. The xpos argument specifies the horizontal value, and the ypos argument specifies the vertical value.
               InputBox("Enter the Answer Here","Answer","Your Answer Here",500,800)

helpfile and context

The helpfile argument specifies a Windows Help file to open if the user presses the f1 button. If you specify a Help file, you also need to specify a context id.
The context argument specifies a Help context id number for the file called in the helpfile argument. The Help context id number opens the corresponding Help topic.

Message Box

The message box is useful when you want to notify a user that an event has occurred. You can specify the buttons shown in the dialog, and the function returns a value that indicates which button was clicked:
MsgBox(prompt, buttons, title, helpfile, context)
The helpfile and context arguments in the MsgBox function are optional.

prompt

The prompt argument is a string value of up to 1024 characters.

buttons

The buttons argument is a VBScript constant or a numeric value that determines which buttons are displayed on the dialog. The list shows the values and constants that you can use when calling this function.
Value
Buttons shown
0
OK
1
OK, Cancel
2
Abort, Retry, Ignore
3
Yes, No, Cancel
4
Yes, No
5
Yes, No, Cancel
16
(Critical Message Icon)
32
(Warning Query Icon)
48
(Warning Message Icon)
64
(Information Message Icon)
0
(First button default)
256
(Second button default)
512
(Third button default)
0
(User must respond before continuing with application)
4096
(User must respond before continuing with the operating system)
Example :
msgbox "The Name is Invalid",2+48,”Error Message”

title

The title argument is a string that specifies the text shown in the titlebar of the message box. If no title is specified, the title of the calling application is displayed.

Helpfile and Context

These arguments work the same as for InputBox. Helpfile specifies a Windows Help file, and context specifies the Help context id for the topic.

Message Box Returning Value

The return values for the MsgBox function are the numeric or constant values of the button pressed. The list  below shows the possible return values for the MsgBox function.
Button Clicked
Value
OK
1
Cancel
2
Abort
3
Retry
4
Ignore
5
Yes
6
No
7
(Please note : for Value returning message box the arguments must be enclosed within parentheses.)


Example :
<HTML>
<HEAD>
<TITLE>The MsgBox Returns</TITLE>
</HEAD>
<BODY>
<H1>Return Value in Message Box</H1>
<HR COLOR="BLUE">
<INPUT TYPE="Button" NAME="Btn1" VALUE="  Exit  ">
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Btn1_OnClick()
dim ans
ans=msgbox("Are you sure to exit",4+32,"Exit Window Message")
if ans=6 then
                msgbox "You click Yes button" &vbcrlf &"So you are exiting window"
else
                msgbox "You click No button"
end if
End Sub
-->
</SCRIPT>
</BODY>
</HTML>


Session 5                                                              VBScript Function II

String Functions

The following string functions act on string data to allow you to manipulate and parse strings. Parsing textual data means dividing it into logical divisions.

Asc

The Asc function takes a string as a parameter and returns the ASCII character code for the first character in the string:
Example :
<html>
<input type="submit" name="btnsub">
</html>
 
<script language="VBScript">                                                       
sub btnsub_onclick()
Dim strData, intCharCode
 
strData = "This is a string"
 
intCharCode = Asc(strData)
 
msgbox intCharCode
end sub
</script>
 
In this code example, the function returns the value of T, which is 84. If you run this function on an empty string, it generates a runtime error.

Chr

The Chr function takes a character code as a parameter and returns the corresponding character. Keep in mind that the characters for codes 0 to 31 are nonprintable:
StrMyString = "This is my two line" + (Chr(13) + Chr(10)) + "text string example."
                    Chr(13)=Carriage return
                    Chr(10)=Line Feed
In this example line, the string has a carriage return and a line feed added to the middle of the text. This will cause a break in the string, displaying it on two lines.

InStr

The InStr function is a powerful text-searching tool that finds the position of text substrings within strings of text.
position = InStr(startpos, string1, string2, type)
The InStr function returns the position of the substring within the string. In this case, the return value is held by the variable position. Let's go through the other arguments individually.

Startpos

The startpos argument is a numeric value that tells the function where to start searching

String1

The string1 argument is the string in which you are searching for the string2 string.

String2

String2 is the text for which you're searching.

Type

The type argument specifies the string comparison that you're performing. This argument can have a value of 0 (default) or 1. A type 0 comparison is a binary comparison. The function will return a position only in the case of an exact match. An argument of 1 will do a non-case-sensitive, textual search.


Example
<html>
<input type="submit" name="btnsub">
<script language="VBScript">
sub btnsub_onclick()
Dim a,b,c,d                                                                   
a = "This is the big string"
b = "big"
c = InStr( 1, a, b, 0)
msgbox c
end sub
</script>
</html>
 

Table showing Return values for the InStr function.

String Values
Return Values
mainstring length is 0
0
mainstring is Null
Null
searchstring length is 0
startpos
searchstring is Null
Null
searchstring not found
0
searchstring found
(position of string in mainstring)
If the value of startpos is greater than the length of mainstring, the function returns a 0.


Left

The Left function returns a string containing the characters from the left side of the string, up to a specified number. The function takes two arguments, string and length:
Example
<html>
<input type="submit" name="btnsub" Value="My String">
</html>
<script language="VBScript">
sub btnsub_onclick()                                                                                           
Dim strMyString, strMain
strMain = "College of Software Engineering"
strMyString = Left(strMain, 20)
msgbox strMyString
end sub
</script>
In this example the string variable strMyString would return the first twenty characters of the string. If the number you specify in the length argument is greater than or equal to the length of the string, the function will return the entire string.

Mid

The Mid function returns a substring of a specified length from another string. This function takes three parameters: string, start, and length. The length argument is optional.
Dim strMyString, strMain
strMain = "Do not Ask for credits"
strMyString = Mid(strMain, 8, 10)
In this example, we're looking for a string that starts at character 8 and is 7 characters in length. The string value contained in strMyString is equal to “Ask for”.

Right

The Right function works like the Left function, but it returns a specified number of characters starting from the last character in the string. This function takes the number of characters as an argument and returns a string:
Dim strMyString, strMain
strMain = "How now brown cow?"
strMyString = Right(strMain, 10)
In this example, strMyString is set to the last 10 characters of strMain, or brown cow?.

LTrim

The LTrim function returns a copy of the string argument with the leading spaces removed from the string:
Dim strMyString, strMain
strMain = "    There are four leading spaces here."
strMyString = LTrim(strMain)
In this example, the functions returns the string, "There are four leading spaces here."

RTrim

The Rtrim function works like the Ltrim function. It removes trailing spaces from a string. It takes a single argument, string, and returns a string.

Str()

The Str()function takes a number as an argument and returns a string value representing the number. The first character in the resulting string is always a space that acts as a placeholder for the sign of the number. If you want to use a numeric value in a string or a function that takes a string as a parameter, you'll need to use this function or the CStr function to make the conversion first.

StrComp

The StrComp function takes two strings as arguments and compares them, based on the third argument, which defines the type of comparison:
The StrComp function returns a numeric value that indicates whether the items are the same. The comparison type has two possible values: 0 (default) is a binary comparison, and 1 is non-case-sensitive. The Table  show the return values for the StrComp function.
Table  Return values for the StrComp function.

Return Value
Description
-1
String1 < String2
0
String1 = String2
1
String1 > String2
NULL
One of the strings is null

Example

<html>
<input type="submit" name="btnsub" Value="String Compare">
</html>
<script language="VBScript">
sub btnsub_onclick()
Dim RetVal, strString1, strString2
strString1 = "This is a ram."                                                                 
strString2 = "This is a pen."
RetVal = StrComp(strString1, strString2, 0)
if RetVal = -1 then
                msgbox "String1 < String2"
elseif RetVal = 0 then
                msgbox "String1 = String2"
else
                msgbox "String1 > String2"
end if
end sub
</script>

String

The String function takes a number and character code(ascii code) argument and returns the character, repeated a number of times:
Dim strRetString
strRetString = String(3, 97)
               character code 97 =’a’
This example returns the string "aaa". If the character code argument is greater than 255, the code is automatically converted to a valid character using the formula charcode = (char Mod 256).

Trim

The Trim function returns the string argument, with leading and trailing spaced removed.

LCase

The LCase function takes a string and converts all the characters to lowercase. It takes a string as an argument and returns the converted string.

UCase

The UCase function converts all the characters in the string argument to uppercase.

Val

The Val function takes a string argument and returns numbers from the string. The function stops retrieving numbers as soon as it hits a non-numeric character:
 
Dim MyNumber, strMyString
 
MyString = "300 South Street"
 
MyNumber = Val(strMyString)
 
In this example, the function returns the number 300.

Conversion Functions

Conversion functions enable you to change the subtype of a variable. Although VBScript uses the variant type for all variables, in many cases an argument of a certain type is required. An example would be a function that takes a string argument. If you want to be able to use numeric data, you'll need to convert it to a string before calling the function.

CByte

The Cbyte function converts an expression to the subtype byte.

CDbl

The CDbl function converts an expression to the subtype double.

CInt

The CInt function converts an expression to the subtype integer.

CLng

The CLng function converts an expression to the subtype long.

CStr

The CStr function returns a string from a valid expression.

Time and Date Functions

You'll find time and date functions extremely useful in customizing your Web pages. You can add automatic time and date stamping to pages, and you can write programs that provide useful calendar functions.

Date

The Date function takes no arguments and returns the current system date.

DateSerial

The DateSerial function takes year, month, and day arguments and returns a variant of subtype date. The year argument can be any year between 100 and 9999. The month and day arguments are numeric values.

DateValue

The DateValue function takes a string argument containing a valid date and returns a variant of subtype date. This is an extremely useful function, because it interprets a number of formatted date strings. For example, you could use "January 1, 1999," "1/1/99," or "Jan 1, 1999" as an argument. Once the date is a variant of subtype date, other date functions can be used on it.

Day

The Day function takes a date argument and returns the day as a numeric value between 1 and 31.

Hour

The Hour function takes a time argument and returns an hour value between 0 and 23.

Year

The Year function takes a date value and returns the year.

Weekday

The Weekday function takes a date and optionally a firstdayofweek argument and returns a numeric value representing the day of the week. If firstdayofweek isn't specified, the function defaults to Sunday. The settings for firstdayofweek are shown in Table .
Table  Day constants.
Day
Numeric Value
System *
0
Sunday
1
Monday
2
Tuesday
3
Wednesday
4
Thursday
5
Friday
6
Saturday
7
*This value is used only in the firstdayofweek argument and is not a return value.
Example
<HTML>
<HEAD>
<TITLE>Day of the week</TITLE>
</HEAD>
<BODY>
<H1>What day did it happen?</H1>
<HR COLOR="BLUE">
Enter any valid date and click the button to find out what day it was!<BR>
<INPUT TYPE="TEXT" NAME="TxtDate"><BR>
<INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Tell me the day of the week">
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Btn1_OnClick()
    Dim DayVal, Message, MyDate
    MyDate = DateValue(TxtDate.Value)
    DayVal = Weekday(MyDate)
        If DayVal = 1 then Message = "Sunday"
        If DayVal = 2 then Message = "Monday"
        If DayVal = 3 then Message = "Tuesday"
        If DayVal = 4 then Message = "Wednesday"
        If DayVal = 5 then Message = "Thursday"
        If DayVal = 6 then Message = "Friday"
        If DayVal = 7 then Message = "Saturday"
    Message = "It happened on a " + Message + "."
    MsgBox Message, 64,"When did it happen?"
End Sub
-->
</SCRIPT>
</BODY>
</HTML>
 
The web page looks  as follow :




Minute

The Minute function retrieves the minute value of a time value.

Month

The Month function returns a numeric value for the month from a valid date.

Now

The Now function returns the current date and time from the client machine. This function takes no arguments.

Second

The Second function returns the seconds value from a time value.

Time

The Time function returns the current system time as a date subtype variant.

TimeSerial

The TimeSerial function takes hours, minutes, and seconds as arguments and returns a variant of subtype date. The hour argument is an integer between 0 and 23.

TimeValue

The TimeValue function takes a string containing a valid time and returns a variant of subtype date containing the time.
You can use this function to get input from the user and convert it to a date format. Valid values for the time argument include times from 12- and 24-hour clocks.
Creating a Dynamic Calendar
<HTML>
<HEAD>
<TITLE>Yearly Calendar</TITLE>
<SCRIPT LANGUAGE=VBS>
Sub JANUARY_onClick()
    DisplayMonth(1)
End Sub
Sub FEBRUARY_onClick()
    DisplayMonth(2)
End Sub
Sub MARCH_onClick()
    DisplayMonth(3)
End Sub
Sub APRIL_onClick()
    DisplayMonth(4)
End Sub
Sub MAY_onClick()
    DisplayMonth(5)
End Sub
Sub JUNE_onClick()
    DisplayMonth(6)
End Sub
Sub JULY_onClick()
    DisplayMonth(7)
End Sub
Sub AUGUST_onClick()
    DisplayMonth(8)
End Sub
Sub SEPTEMBER_onClick()
    DisplayMonth(9)
End Sub
Sub OCTOBER_onClick()
    DisplayMonth(10)
End Sub
Sub NOVEMBER_onClick()
    DisplayMonth(11)
End Sub
Sub DECEMBER_onClick()
    DisplayMonth(12)
End Sub

Sub DisplayMonth(imonth)
dim MonthName(12)
MonthName(1)="January"
MonthName(2)="February"
MonthName(3)="March"
MonthName(4)="April"
MonthName(5)="May"
MonthName(6)="June"
MonthName(7)="July"
MonthName(8)="August"
MonthName(9)="September"
MonthName(10)="October"
MonthName(11)="November"
MonthName(12)="December"
document.clear
document.write "<CENTER>"
document.write "<FONT FACE='Verdana' SIZE=5>"
document.write MonthName(imonth) & " " & Year(date)
document.write "<P>"
document.write "<TABLE CELLPADDING=10 BORDER bgcolor=gold><TR>"
document.write "<TD><B>Sun<TD><B>Mon<TD><B>Tue<TD><B>Wed<TD><B>Thu<TD><B>Fri<TD><B>Sat"
document.write "<TR>"
    firstdate=DateSerial(year(date), imonth, 1)
    thisdate=firstdate
    nextday=1
    For cday=1 to 7
        If WeekDay(thisdate)>cday Then
            document.write "<TD></TD>"
        else
            document.write "<TD ALIGN=CENTER><FONT SIZE=3>" & nextday & "</TD>"
            nextday=nextday+1
            thisdate=DateSerial(year(date), imonth, nextday)
        End If
    Next
    document.write "<TR>"

    weekDays=1
    while month(thisdate)=imonth
        document.write "<TD ALIGN=CENTER><FONT SIZE=3>" & nextday & "</TD>"
        nextday=nextday+1
        weekDays=weekDays+1
        If weekDays>7 then
            WeekDays=1
            document.write "<TR>"
        End If
        thisdate=DateSerial(year(date), imonth, nextday)
    wend
document.write "</TABLE>"
document.write "</CENTER>"
document.close

End Sub
</SCRIPT>
</HEAD>
<BODY>
<FONT FACE="Comic Sans MS">
<CENTER>
<H1>Yearly Calendar</H1>
Click on a month to see a weekly calendar
<P>
<FONT FACE="Verdana" SIZE=6>
<TABLE CELLPADDING=10 BORDER>
<TR>
<COLGROUP>
<COL ALIGN=CENTER>
<COL ALIGN=CENTER>
<COL ALIGN=CENTER>

<TD><INPUT TYPE=BUTTON NAME="January" VALUE="JANUARY">
<TD><INPUT TYPE=BUTTON NAME="February" VALUE="FEBRUARY">
<TD><INPUT TYPE=BUTTON NAME="March" VALUE="MARCH">
<TR>
<TD><INPUT TYPE=BUTTON NAME="April" VALUE="APRIL">
<TD><INPUT TYPE=BUTTON NAME="May" VALUE="MAY">
<TD><INPUT TYPE=BUTTON NAME="June" VALUE="JUNE">
<TR>
<TD><INPUT TYPE=BUTTON NAME="July" VALUE="JULY">
<TD><INPUT TYPE=BUTTON NAME="August" VALUE="AUGUST">
<TD><INPUT TYPE=BUTTON NAME="September" VALUE="SEPTEMBER">
<TR>
<TD><INPUT TYPE=BUTTON NAME="October" VALUE="OCTOBER">
<TD><INPUT TYPE=BUTTON NAME="November" VALUE="NOVEMBER">
<TD><INPUT TYPE=BUTTON NAME="December" VALUE="DECEMBER">
</TABLE>
<font color=blue size=4>
 <br>College of Software Engineering
</BODY>
</HTML>

The Web page will be displayed as :









Session – 6

Interfacing VBScript with an HTML Form


Before Building an HTML Form to Work with VBScript the hierarchy of HTML objects. A document is an object that belongs to the window object (that is, the window object is its parent). Because the window object is implicit, you usually do not need to specify it in the code line. You can have only one document per window; however, a frame is treated as a window.
A form object belongs to the document, and a document can have any number of forms. The element objects-such as text boxes and other input controls-are objects that belong to the form, and again, a form can have any number of elements. To access the value of a form element from your script, you use the following syntax:
                    Document.FormName.ElementName.Value
Whenever building  a HTML form that you intend to interface using VBScript, you must give your form and its elements a name. Giving them names simplifies matters greatly, although it is not absolutely necessary. Lets see the example below :
<HTML>
<HEAD>
<SCRIPT LANGUAGE="vbscript">
Sub CommandButton1_OnClick
    strTheInput = Document.Forms(0).Elements(0).Value
    Alert strTheInput
End Sub
 </SCRIPT>
 </HEAD>
 <BODY>
 <FORM>
  <INPUT TYPE="text">
  <INPUT TYPE="button" NAME="CommandButton1" VALUE="Click Me">
 </FORM>
 </BODY>
</HTML>
In this example, neither the form nor the text box has a name. VBScript places all forms into an array of forms, starting at number 0; it also places all form elements, such as buttons and text boxes, into an elements array, again starting at number 0.
To access the contents of this text box, you must know within which form it resides and the text box's ordinal number within the form.

Events in VBScript

When we say an Event , it means any action performed by the user in order to perform certain task or tasks. E.g. clicks a button. Clicking a button generates an event. Events in Windows generate messages. Messages in Windows tell the applications and the operating system what to do and what's going on.
Most of the objects that you place into your HTML documents will have events to which you can attach script code. The Button control you've been using so far has an onClick event. When this event occurs, code in the onClick procedure runs.

Intrinsic Controls

Working with TextBoxes

The Text type input control is used to retrieve input from the user. Its use is fairly straightforward, and because it is the default type for the Input control, you don't even need to explicitly declare it. The following two lines of code are functionally equivalent:
<INPUT TYPE=TEXT NAME=Txt1>
 
<INPUT NAME=Txt2>
Setting the value property for the control inserts text into it. You can set the defaultValue property initially to place text into the control.
Text properties.
Property
Description
DefaultValue
Value of control at creation
Enabled
Control is enabled (1) or disabled (0)
Form
Form to which the control belongs
Name
The name of the control
Value
Content of the control
The tables below show the methods and Events of TextBox..
Text methods.
Method
Description
focus
Give control input focus
blur
Remove focus from control
select
Select text in control


Text events.
Events
Description
onFocus
Control gets focus
onBlur
Control loses focus
onChange
Value property of the control changes
onSelect
Control is selected



Example :
<HTML>
<HEAD>
<TITLE>Text Box Control</TITLE></HEAD>
<BODY>

<H2>Event Properties and Methods for TextBox</H2><HR COLOR="BLUE">

<INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Text 1">
<INPUT TYPE="SUBMIT" NAME="Btn2" VALUE="Text 2">
<BR><BR>
Text 1<INPUT TYPE="TEXT" NAME="Txt1"><BR>
Text 2<INPUT TYPE="TEXT" NAME="Txt2"><BR>

<SCRIPT LANGUAGE="VBScript">
<!--
Sub Btn1_OnClick
    Txt1.Focus          'Focus method was called
End Sub
Sub Btn2_OnClick
    Txt2.Select
End Sub

Sub Txt1_OnFocus
    MsgBox "Text 1 Focused!"
End Sub

Sub txt1_OnBlur     ' When the control lost its focus
                if txt1.value="" then
                                msgbox "You must input data in text1"
                                txt1.select
                end if
End Sub

-->
</SCRIPT>
</BODY>
</HTML>

Hidden

The Hidden input type is used to store a value in a form that is invisible to the user. This control is especially used in ASP pages when the values are passed from invisible controls to the server.

Textarea

The Textarea control is similar to the Text type control in that you can use it to enter text on a page. The textarea allows you to enter multiple lines of text, making it more suitable for larger data input. The textarea is not usually an input tag with a type attribute, although that form is allowed. The textarea is a two-sided tag consisting of a <TEXTAREA></TEXTAREA> tag pair. The initial value of the textarea is contained between these tags.
Textarea properties.
Method
Description
cols
Number of columns in control
defaultValue
Value of control at creation
enabled
Control is enabled (1) or disabled (0)
form
Form to which control belongs
name
Name of the textarea
rows
Number of rows in control
value
Content of the control
The rows and cols properties allow you to control the size of the textarea:
<TEXTAREA NAME=Text1 ROWS=30 COLS=40></TEXTAREA>

 

The Radio Button Control

The radio button control is useful when you want to present several choices to the user, but you only want the user to choose one of those choices. For example, you might want the user to specify whether he or she is male or female.The radio button control makes it easy to require the user to only choose one option.

Syntax :

            <INPUT TYPE="RADIO" NAME="name" VALUE="value" checked>

where type=”Radio” creates the radio button.Name is the name of the radio button and value is the return value when radio button is checked. “checked” is optional making the button default checked.

Example on Radio Button

<HTML>

<HEAD>

<TITLE>The Radio Button Control</TITLE>

</HEAD>

<BODY>

<h2>The Radio Button Control</h2>

<P>This Web page demonstrates how to place a simple group of

radio button controls on a Web page.  When the user clicks on

a radio button, VBScript calls a subroutine that

tells you which button the user has selected.

<P>

<INPUT TYPE="RADIO" NAME="optGender" LANGUAGE="VBScript"

OnClick="SetGender('male')  "> Male<BR>

<INPUT TYPE="RADIO" NAME="optGender" LANGUAGE="VBScript"

OnClick="SetGender('female')"> Female<BR>

<P>

<INPUT NAME="txtResult" SIZE="50">

<SCRIPT LANGUAGE="VBScript">

<!--

   Sub SetGender(Gender)

      txtResult.Value = "You have selected " & Gender & "."

   End Sub

-->

</SCRIPT>

</BODY>

</HTML>


 

 

Checkbox

The Checkbox control allows you to give the user a choice to check on a page. The check box control cab be used for a single or multiple selection because their checked values are independent of other Checkbox controls. The Table lists the Checkbox properties.
Checkbox properties.

Property
Description
Checked
Checkbox is checked
DefaultChecked
Checkbox is checked by default
Enabled
Control is enabled (1) or disabled (0)
Form
Name of the form to which the control belongs
Name
Name of the checkbox
Value
Checkbox value

The checkbox control has two events, onClick and onFocus, and two methods, click and focus.

 

Select

The Select control is instantiated in code using the <SELECT></SELECT> tag pair. It is similar to a Windows Listbox control. You set the items in the Select control using the <OPTION> tag. You can determine the item that your user selects, using either the selectedIndex property or the options property.
 Select control properties.
Property
Description
name
Name of the control
length
Number of items in the control
options
Array of options for the control
selectedIndex
Index of the currently selected item
size
Number of items displayed (default is 1)
The methods available to the Select control are focus and blur. Events for the Select control include onBlur, onFocus, and onChange.
The easiest way to use this control in VBScript is to get the selectedIndex from the control and then to act on that value using a Select Case statement.
The Button Control
Buttons are commonly used to give the user the ability to execute VBScript code that performs some action.
Syntax :
<INPUT TYPE="Button" NAME="cmdGetCost" VALUE="Get the Cost">
Here, the name of the control is cmdGetCost and the caption that will appear to the user on the Web page is "Get the Cost."
Example showing the usage of Button Control
<HTML>
<HEAD>
<TITLE>Tester Page</TITLE>
</HEAD>
<BODY>
<H1>Tester Page for VBScript</H1>
<HR COLOR="BLUE">
<INPUT TYPE="SUBMIT" NAME="Btn1" VALUE="Click to test the code">

<SCRIPT LANGUAGE="VBScript">
<!--
     Sub Btn1_OnClick
     Btn1.Value = "Value is changed!"
     End Sub
-->
</SCRIPT>
</BODY>
</HTML>
(Please Note : There are two more button types “Submit” and “Reset” which will post the form elements values to server and Resets the Form elements values respectively.)


Session – 7

Checking Form Data (Validation)


Alerting Users During the Data Entry

Prior to submission, while the user is entering data, you can use several methods to alert the user to a problem with his input. For example the text box has an OnChange ,OnBlur event that fires when the focus moves away from the text box  to validate the input data.

 

A Data Verification Example

The source code shows the validations. The Web page when it's run in the browser. It contains five HTML text boxes. The first is an optional field that contains no verification. Two fields require a numerical entry, one requires a date, and one asks for the user's e-mail address. As the user enters data and moves to the next field, the data is verified, and if the script finds a problem, it alerts the user. The verification takes place in a series of functions that can be called from any of the fields, which allows for speedy maintenance should you need to add further verifiable fields to the form. Finally, the user clicks the submit button, which is a normal button. The data is reverified, and if it's found to be correct, the form data is submitted to the server.
<HTML>
<HEAD>
<TITLE>Data Validation</TITLE>

<SCRIPT LANGUAGE="vbscript">

Function ValidateNumber(ByVal TheNumber, ByVal FieldName)
 If Not IsNumeric(TheNumber) Then
  x = MsgBox("Invalid Numeric Entry",16,FieldName)
  ValidateNumber = False
 Else
  ValidateNumber = True
 End If
End Function

Function ValidateDate(ByVal TheDate, ByVal FieldName)
 If Not IsDate(TheDate) Then
  x = MsgBox("Invalid Date",16,FieldName)
  ValidateDate = False
 Else
  ValidateDate = True
 End If
End Function

Function IsEMail(ByVal TheEMail, ByVal FieldName)

 If InStr(TheEMail, "@") > 2 Then
    If Len(TheEMail) - InStr(TheEMail, "@") > 6 Then
       If InStr(InStr(TheEMail, "@"),TheEMail,".") > 0 Then
          If Len(TheEMail) - InStr(InStr(TheEMail, "@"),TheEMail,".") => 2 Then
             ValidateEMail = True
          Else
             ValidateEMail = False
          End If
       Else
          ValidateEMail = False
       End If
    Else
       ValidateEMail = False
    End If
 Else
    ValidateEMail = False
 End If

 If ValidateEMail = True Then
    IsEMail = True
 Else
    x = MsgBox("Invalid Entry",16,FieldName)
    IsEMail = False
End If

End Function


Sub txtQty_OnChange
 x = ValidateNumber(Document.Form1.txtQty.Value, "Quantity")
End Sub

Sub txtSize_OnChange
 x = ValidateNumber(Document.Form1.txtSize.Value, "Size")
End Sub

Sub txtDate_OnChange
 x = ValidateDate(Document.Form1.txtDate.Value, "Date")
End Sub

Sub txtEmail_OnChange
 x = IsEMail(Document.Form1.txtEmail.Value, "EMail")
End Sub

Sub cmdButton1_OnClick
  If ValidateNumber(Document.Form1.txtQty.Value, "Quantity") And _
    ValidateDate(Document.Form1.txtDate.Value, "Date") And _
    ValidateNumber(Document.Form1.txtSize.Value, "Size") And _
    IsEMail(Document.Form1.txtEmail.Value, "EMail") Then
      Document.Form1.Submit
  Else
      Exit Sub
  End If
End Sub

</SCRIPT>

</HEAD>

<BODY BGCOLOR="white">
<FORM NAME="Form1" ACTION="http://www.vbscripts.com/test/formtest.phtml"
METHOD=POST>
<PRE>
Your Name       <INPUT TYPE="text" NAME="txtUserName">
Quantity        <INPUT TYPE="text" NAME="txtQty">
Size in Metres  <INPUT TYPE="text" NAME="txtSize">
Date            <INPUT TYPE="text" NAME="txtDate">
Your EMail      <INPUT TYPE="text" NAME="txtEmail">
<INPUT TYPE="Button" NAME="cmdButton1" VALUE="Submit Now">
</PRE>
</FORM>
</BODY>
</HTML>

The Web page display like :
 

Creating the Form

The form itself is a straightforward HTML form; no surprises here. The form's action is left blank. The HTML for the form is shown in the following code block:
<FORM NAME="Form1" ACTION="" METHOD=POST>
<PRE>
Your Name       <INPUT TYPE="text" NAME="txtUserName">
Quantity        <INPUT TYPE="text" NAME="txtQty">
Size in Metres  <INPUT TYPE="text" NAME="txtSize">
Date            <INPUT TYPE="text" NAME="txtDate">
Your EMail      <INPUT TYPE="text" NAME="txtEmail">
<INPUT TYPE="Button" NAME="cmdButton1" VALUE="Submit Now">
</PRE>
</FORM>

 

Validating Numeric Data Entries

Each of the verifications is held in a separate function. Functions in VBScript are procedures that return a value to the code that called them. The following code is the function that validates the numerical data:
2:Function ValidateNumber(ByVal TheNumber, ByVal FieldName)
3: If Not IsNumeric(TheNumber) Then
4:  x = MsgBox("Invalid Numeric Entry",16,FieldName)
5:  ValidateNumber = False
6: Else
7:  ValidateNumber = True
8: End If
9:End Function
The function prototype in line 2 requires that two values are passed into the function: first, TheNumber, which is the value to be validated, and second, FieldName, which is the name of the field being validated.
The keyword ByVal instructs the scripting engine to pass only the value of these variables into the function.
Line 3, where the actual verification takes place, Suppose x equals 10. The statement If x = 10 Then returns True, and the lines following the If... statement execute. The VBScript built-in function IsNumeric is used to check for the numeric type of data.. If the entered string can be converted to a number, the function returns True; if it cannot be converted, the function returns False. Remember that all data coming from an HTML form is string data; for instance, the number 400 appears to the program as "400".

Validating Date Entries

The function for validating the date in this example is very similar to the numerical validation function: The IsDate built-in function is used to validate date field.
10:Function ValidateDate(ByVal TheDate, ByVal FieldName)
11: If Not IsDate(TheDate) Then
12:  x = MsgBox("Invalid Date",16,FieldName)
13:  ValidateDate = False
14: Else
15:  ValidateDate = True
16: End If
17:End Function

Verifying String Data Entries

Verifying string data can become somewhat complicated because you must decide what the string pattern should look like and hard code that pattern into the script, as the following code shows:
18:Function IsEMail(ByVal TheEMail, ByVal FieldName)
 
19: If InStr(TheEMail, "@") > 2 Then
20:    If Len(TheEMail) - InStr(TheEMail, "@") > 6 Then
21:       If InStr(InStr(TheEMail, "@"),TheEMail,".") > 0 Then
22:          If Len(TheEMail) - InStr(InStr(TheEMail,    
                                             "@"),TheEMail,".") => 2 Then
23:             ValidateEMail = True
24:          Else
25:             ValidateEMail = False
26:          End If
27:       Else
28:          ValidateEMail = False
29:       End If
30:    Else
31:       ValidateEMail = False
32:    End If
33: Else
34:    ValidateEMail = False
35: End If
 
36: If ValidateEMail = True Then
37:    IsEMail = True
38: Else
39:    x = MsgBox("Invalid Entry",16,FieldName)
40:    IsEMail = False
41:End If
 
42:End Function
The pattern of an e-mail address at minimum should be ***@***.***, where * is alphanumeric. Lines 19 to 22 check for this minimum pattern.
Line 19 uses the InStr function to find the @ character somewhere in the string. InStr returns the position of the character if found or 0 if it is not found within the search string. The criteria you set for the first part of the pattern is that the @ character must appear at least three characters in from the left. As a result, the InStr function in line 19 must return at least 3 for the first part of the pattern to be true.
If the first part succeeds, the second part of the pattern dictates that there must be a minimum of seven characters after the @ symbol. Line 20 tests this condition by subtracting the position of the @ symbol from the length of the overall string, which is found with the Len function.
20:    If Len(TheEMail) - InStr(TheEMail, "@") > 6 Then
In the minimum pattern, the length of the string is 11 characters, and the @ symbol resides at position 4; therefore, the minimum number of characters to the right of the @ is 7. Line 20 tests for any amount greater than 6.
The next stage is a little more complex. Line 21 determines whether a . (period) appears somewhere after the @ symbol. Notice that the InStr function appears twice in line 21:
21:       If InStr(InStr(TheEMail, "@"),TheEMail,".") > 0 Then
The full syntax of InStr is
InStr(Start,String1,String2)
In Line 21, you use the position of the @ symbol to determine where InStr should start its search for the . symbol. If it does find a . symbol somewhere after the @ symbol, the function returns the position of the character, and you can proceed to the final part of the pattern, which is determining whether the . symbol appears at least two characters in from the right. As you know, the e-mail address could be a .com, .edu, .com.bh, .co.uk, and so on.
22:          If Len(TheEMail) - InStr(InStr(TheEMail, "@"),TheEMail,".") => 2
                                         Then
Line 22 uses the position of the @, the position of the ., and the overall length of the string to determine how many characters appear after the . symbol. Two or more characters at the end makes the pattern complete and fits our definition of the minimum e-mail address. Of course, as I said earlier, this doesn't stop someone from entering aaa@aaa.aaa.
If the validation of the e-mail address fails at any stage, the variable ValidateEmail is set to False. Finally, the script makes a check of the variable, and if all is well, the function's own return value is set to True. If the data is invalid, the return value is set to False, and a warning message is displayed to the user.

Implementing an OnChange Event

When the user enters a new or changed value in one of the text boxes and then moves away from that text box, an OnChange event fires. The following segment shows the event handlers for each of the text boxes, not including the first text box, which is not validated:
43:Sub txtQty_OnChange
44: x = ValidateNumber(Document.Form1.txtQty.Value, "Quantity")
45:End Sub
 
46:Sub txtSize_OnChange
47: x = ValidateNumber(Document.Form1.txtSize.Value, "Size")
48:End Sub
 
49:Sub txtDate_OnChange
50: x = ValidateDate(Document.Form1.txtDate.Value, "Date")
51:End Sub
 
52:Sub txtEmail_OnChange
53: x = IsEMail(Document.Form1.txtEmail.Value, "EMail")
54:End Sub
 

Implementing a Validate and Submit Routine

As mentioned in the introduction to the chapter, the main goal of data validation is to reduce the amount of poor data or to eliminate it altogether.
Only after all the validation checks that you specify are completed successfully is the data submitted to the server, as you can see from the following code:
55: Sub cmdButton1_OnClick
56:  If ValidateNumber(Document.Form1.txtQty.Value, "Quantity") And _
57:    ValidateDate(Document.Form1.txtDate.Value, "Date") And _
58:    ValidateNumber(Document.Form1.txtSize.Value, "Size") And _
59:    IsEMail(Document.Form1.txtEmail.Value, "EMail") Then
60:      Document.Form1.Submit
61:  Else
62:      Exit Sub
63:  End If
64:End Sub
Lines 56 through 59 are actually the same line, joined together at runtime with the special underscore character. All checks must return True for the overall statement to be True.
Using the OnSubmit Event
OnSubmit is an event and, as such, the code attached to that event should be within an event handler. But the OnSubmit event must be used as though it is a function. eg.
Function myForm_OnSubmit()
This is done so that OnSubmit can return a value. OnSubmit returns True if the form data is validated, in which case the form data is submitted; it returns False if the form data fails validation, in which case the form data is not submitted.
Within the OnSubmit event handler/function, you can include calls to all your validation routines, as this amendment to the previous example shows:
55:Function Form1_OnSubmit
56:  If ValidateNumber(Document.Form1.txtQty.Value, "Quantity") And _
57:    ValidateDate(Document.Form1.txtDate.Value, "Date") And _
58:    ValidateNumber(Document.Form1.txtSize.Value, "Size") And _
59:    IsEMail(Document.Form1.txtEmail.Value, "EMail") Then
60:      Form1_OnSubmit = True
61:  Else
62:      Form1_OnSubmit = False
63:  End If
64:End Sub
To use this code with the previous example, you would also have to change the button control type to Submit.


Session: 8

The Scripting Model

 

Windows, Documents, and Frames

The Internet Explorer scripting model is made up of a hierarchy of objects, with the window representing the most important object, the document and the frames objects. The discussion of the Internet Explorer scripting model begins with an overview of these three objects, the properties and methods they provide, and how you can use them to control Internet Explorer.
The various objects through which you can control the behavior of Internet Explorer form a hierarchy. The window object is the top level object in this hierarchy and acts as a container for all other objects. This object is the browser's window you see on-screen; moreover, every parameter of the window you can adjust through VBScript code is a property of the window object. For example, the name of the window is a property of the window object. You can find out the name of the window from within your script with a statement like the following one:
wName=window.name
Another property of the window object is the status property, the text displayed in the status bar of the browser window. You can find out the current status message with the statement:
statusMessage=window.status
You can also set the status message with statements like these:
window.status="Thanks for visiting our site!"
or
window.status="Date "& date & " Time " & time
The window object's property you will use the most is the document property, which represents the document displayed on the window. This property is actually another object, with its own properties. The document has a background color, whose value can be manipulated with the document's bgColor property. To access the bgColor property of the document object, you can use a statement like the following one:
window.document.bgColor=red
Because the document object is the default property of the window object, you can omit the window identifier in the previous line:
document.bgColor=red
The window and the document objects are visible on-screen. Other objects exist that are not visible, but which enable you to control the behavior of Internet Explorer through their properties. The location object is a property of the document object, which enables you to manipulate the URL of the document displayed in the window. One property the location object provides is called href, and is the URL of the document being displayed. This is the URL displayed in Internet Explorer's Address box. To find out the URL of the current document, you must access the href property of the location object of the document object:
thisURL=window.document.location.href
As usual, you can omit the window identifier. The URL is a location property and the location object applies to the document object. Thus, the location is a property of the document, and not the window. href is a property of the location object, which in turn is a property of the document object, which in turn is a property of the window object. You must write down a sequence of objects, starting with the top level object (the window object) and work your way down to the lower-level object whose property you want to access.
A window can also contain frames, which you can access through the frames object. The frames object is an array of objects, the first frame being frames(0), the second one frames(1), and so on. To control the background color of the document in the first frame, you must access the bgColor property of the document of the first frame. Each frame has its own document property similar to the window object. This time we want to access the document of a frame, which in turn is a property of the window object. Instead of getting the window.document.bgColor property as you saw earlier, you must access the document.bgColor of the frames(0) property of the window object:
window.frames(0).document.bgColor
Likewise, you can specify the URL of a document to be displayed in a frame. You start with the href property of the location object, which now must be applied to a frame, and not the window's document. To cause another document to be displayed in the first frame of the window, you must use a statement like:
window.frames(0).location.href
As you can see, the same object can be attached to multiple containers (which are also objects). The window has its own document object, and the document has a location property. If the window contains frames, however, each frame in the window has its own location property. You may find this behavior confusing at first, but you will soon get the hang of it.
In Microsoft's colorful terminology, each entity you see on the browser's window is an object. Objects "expose" some of their properties, which enables you to manipulate them. Some of these properties represent objects themselves, which expose their own properties. The window object exposes the name property, which enables you to examine the name of a window from within your code. To manipulate the background color of the document on the window, you must first access the document property of the window (window.document) and then the bgColor property of the document object (window.document.bgColor).
The following list provides the other objects of the window object, which you will explore in this chapter:
history
history is an object you can use to access the history list of the current window. This is a list of the URLs visited already.
navigator
The navigator object contains information about the browser, such as the name of the browser and its version.
location
The location object provides information about the window's current URL.
document
The most important object of all. It's the actual document in the current window.

The window Object's Properties

Name

Name is a read-only property that returns the name of the window. To create a named window, you must use the TARGET attribute with one of the HTML tags to which it applies. For example, the <A> tag is frequently used with the TARGET attribute, which tells the browser to display the destination HTML document in another window. The HTML line

 
Click <A HREF="http://www.microsoft.com">here</A> to visit the Microsoft Web site.
generates a hyperlink, which displays the root document of Microsoft's Web site when activated in the same window that contains the hyperlink. If you specify the TARGET attribute, however, the same document will appear in a separate window:
Click <A HREF="http://www.microsoft.com" target="MS">here</A> to visit the Microsoft Web site.
If a window with the name MS exists already, the document will be displayed in it. If such a window doesn't exist, a new window opens and the document appears there. You can later refer to this window by its name. For example, you can set the string to appear in the window's status bar using the status property.

Parent

The parent property returns the name of the parent window, which contains the specific window. The parent property of the window object is an object itself, and through its properties, you can adjust the appearance of the parent window.

opener

The opener property returns the window object that opened the current window.:

Self

self is a window object that represents the current window.

top

The top property returns an object that represents the topmost window.

location

The location property returns another object, the location object. The most important property of the location object is the href property, which returns or sets the URL of the current window. The statement
MsgBox window.location.href
 
displays the URL of the current window in a message box.

defaultStatus

This property sets the default text in the status bar. See the description of the status property to find out how you can display a message in the browser's status bar.

status

The status property returns or sets the text displayed in the status bar. The statement
window.status = Now
displays in the status bar the date and time the document was opened. The two status messages were displayed with the statements
window.status="Welcome to SAMS Publishing"
and
window.status="Today's date is " & date & " and the time is " & time
 

Methods

Apart from its properties, the window object provides several methods. The methods are predetermined actions that the window object knows how to perform, such as how to display a message and get input from the user, or how to navigate through the history list (the Web sites visited during the current session) of the window. The window object's methods appear next:

alert

The alert method displays an alert message box. It displays a message and remains on the screen, and the execution of the script is suspended until the user clicks the OK button. You can use the alert method for displaying messages to the user.eg.
alert("Thanks for visiting our site")
 

confirm

confirm displays a message box similar to the alert method, only this box has two buttons, OK and Cancel. The confirm method returns the value True if the OK button is clicked and the value False if the Cancel button is clicked. This method frequently is used to notify the user that an unusual or irrevocable action is about to take place, such as the transmission of Form data to the server. Here's how the confirm method is typically used:
x=window.confirm("Do you want to submit the data?")
if x=True Then Form.submit

prompt

The prompt method prompts the user for data, much like the InputBox() function. The prompt method accepts two arguments, the prompt for the user and an optional default response, and returns the data supplied by the user. The following statement prompts the user for the name of the browser:
browserName=window.prompt("What's your favorite browser?", "Internet Explorer")
Whatever the user has entered in the box gets stored in the browserName variable, which can later be used in the code. If the user simply clicks OK without entering any information, the default response is returned.
Lets try the example for these methods :
<HTML>
<HEAD>
<TITLE>Window Object Methods</TITLE>

<SCRIPT LANGUAGE=VBS>

Sub Alert_onClick()
                alert("Thanks for visiting our site")
End Sub

Sub Confirm_onClick()
                x=window.confirm("Do you want to submit the data?")
                if x=True Then Form.submit
End Sub

Sub Prompt_onClick()
                browserName=window.prompt("What's your favorite browser?", "Internet Explorer")
End Sub

</SCRIPT>

<BODY>
<FONT FACE="Verdana">
<CENTER>
<H1>Windows Methods</H1>
<H4>Click on the following buttons to see some of the methods.
<P>
<INPUT TYPE=BUTTON NAME="Alert" VALUE="Alert">
<INPUT TYPE=BUTTON NAME="Confirm" VALUE="Confirm">
<INPUT TYPE=BUTTON NAME="Prompt" VALUE="Prompt">
</P>
</CENTER>
</BODY>
</FONT>
</HTML>

             

 

 

 

 

 

 

open

The open method opens an existing window, or creates a new one and displays a document in it. This method syntax can become quite lengthy because it accepts a number of arguments:
 
sintax:
[newwindow = ][window.]open url, target, ["[toolbar=bool] [, location=bool]
 
[, directories=bool][, status=bool][, menubar=bool][, scrollbars=bool]
 
[, resizeable=bool][, width=pixels][, height=pixels]"][, top=pixels][, left=pixels]
The arguments in square brackets are optional. The simplest form of the open method is
window.open url, target
where url is the URL of the document to be displayed in the new window and target is the name of the window in which the document will appear. If the window specified with this name exists, this window's contents get replaced by the new document. If not, a new window with this name is opened and the document displays in it. This argument is identical to the TARGET attribute of the <HREF> tag.
The remaining arguments are set to Boolean values (yes/no, or 1/0) and control the appearance of the window.
To hide the new window's toolbar, use the argument "toolbar=no"
To prevent the user from resizing the window, use the argument "resizeable=no".
The last four arguments, which are specified in pixels, don't need to be enclosed in quotes. The arguments width and height determine the window's dimensions, and the arguments top and left determine the window's position on-screen, measured from the screen's top-left corner.
The return value is a window object, which you can use later to close the window. The statement
window.open "http://www.microsoft.com", "MSwindow", "toolbar=no", "menubar=no", "resizeable=no", width=600, height=400
opens the window MSwindow (or creates a new one by that name, if it doesn't exist) and displays the home page of the Microsoft Web site. The MSwindow window has no toolbar and menu. Furthermore, it is 600 pixels wide and 400 pixels tall, and can't be resized.
Example:
 
<HTML>
<HEAD>
<TITLE>WindowOpen</TITLE>
<SCRIPT LANGUAGE=VBS>
 
Sub MS_onClick()
    window.open "http://www.microsoft.com", "window1", "toolbar=no"
 
End Sub
 
 
Sub SAMS_onClick()
    window.open "http://www.mcp.com/sams", "window2","menubar=no"
End Sub
 
 
Sub MSN_onClick()
    window.open "http://www.msn.com", "window3"
End Sub
 
Sub CLGRI_onClick()
    window.open "http://www.caligari.com", "window4"
End Sub
 
Sub INTEL_onClick()
    window.open "http://www.intel.com", "window5"
End Sub
 
Sub NSCAPE_onClick()
    window.open "http://www.netscape.com", "window6"
End Sub
 
 
</SCRIPT>
<BODY>
<FONT FACE="Verdana">
<CENTER>
<H1>Top Web Sites</H1>
<H4>Click on the following buttons to see some of the best Web sites around.
Each Web site will be displayed in a separate window and, if you wish, you  can open them all at once.</H4>
<P>
<INPUT TYPE=BUTTON NAME="MS" VALUE="Microsoft">
<INPUT TYPE=BUTTON NAME="SAMS" VALUE="SAMS">
<INPUT TYPE=BUTTON NAME="MSN" VALUE="MS Network">
<INPUT TYPE=BUTTON NAME="CLGRI" VALUE="Caligari">
<INPUT TYPE=BUTTON NAME="INTEL" VALUE="Intel">
<INPUT TYPE=BUTTON NAME="NSCAPE" VALUE="Netscape">
</P>
</CENTER>
</BODY>
</FONT>
</HTML>
 
The open method has a behavior similar to that of hyperlinks inserted with the <A> tag; however, it gives you more control over the appearance of the new window. The real benefit of using the open method, though, is that it enables you to specify the target at runtime. On the other hand, the destination of the <A> tag must be furnished at design time and can't change when the document is viewed. With the open method, you can navigate to any URL, even a user-supplied URL.

close

The close method closes an open window. If you have opened a window with the following statement
newWindow=window.open "www.msn.com" "w1"
you can close it by calling the close method of the newWindow object:
newWindow.close
 

setTimeout

The setTimeout method sets up a timer to call a function after a specified number of milliseconds. The syntax of the method is
ID = window.setTimeout expression, msec, language
 
where ID identifies the timer object, and can be used with the clearTimeout method, which cancels the timer. expression is the name of a function that will be called when the timer object times out; msec is the number of milliseconds that must pass before the function is called; and language identifies the scripting language of the function (VBScript or Javascript). As usual, the window prefix is optional.
If the user hasn't already switched to another document, you can use the setTimeout method to take some action on a document after so many seconds. For example, you can invoke the method
window.setTimeout GoURL, 10000, VBScript
and supply the following GoURL() subroutine:
Sub GoURL()
 
    window.document.location.href="http://www.someserver.com"
 
End Sub
 
If the user hasn't followed a hyperlink to another page within 10 seconds after the window is opened, the browser will display the home page at the site www.someserver.com.

 

clearTimeout

This method clears the timer with a particular ID. Its syntax is
window.clearTimeout ID
where ID is the value returned by the setTimeout method.

 

navigate

The last method of the window object switches to a particular URL, which is supplied as an argument. The statement
window.navigate http://www.msn.com
 
instructs the browser to connect to the Microsoft Network site and display the site's home page. This method operates identically to setting the window's location.href property to the desired URL.




 



No comments:

Post a Comment

Thanks for comment me