13
VB SCRIPT SELECTED NOTES: If you want to access controls on the form when the page loads, the <SCRIPT> tag must follow the <FORM> tag; otherwise, the script attempts to reference a control that doesn't exist yet. You can retrieve the status of a CheckBox control through its Checked property, and the index of the selected item in a Select control using its SelectedIndex property. To check the state of a radio button, you use the following syntax: If DataForm.RadioButton.Item (0). Checked Then ... That is: If formname.radioButton.Item (index).Checked then… You frequently use VBScript code to react to events raised by controls. For example, buttons, CheckBox and RadioButton controls raise an onclick event when they're clicked The following example uses a TextBox, one Button, and two RadioButton controls; when the push button is clicked, the code converts the TextBox's contents to uppercase or lowercase, according to the RadioButton currently selected: <FORM NAME="DataForm"> <INPUT TYPE=Text NAME="UserName" VALUE=""><BR> <INPUT TYPE=Radio NAME="Case" CHECKED>Uppercase <INPUT TYPE=Radio NAME="Case">Lowercase<BR> <INPUT TYPE=BUTTON NAME="Convert" VALUE="Convert"> </FORM> <SCRIPT LANGUAGE="VBScript"> Sub Convert_Onclick() If DataForm.Case.Item(0).Checked Then DataForm.UserName.Value = UCase(DataForm.UserName.Value) Else DataForm.UserName.Value = LCase(DataForm.UserName.Value) End If End Sub </SCRIPT>

Vb Script Selected Notes

Embed Size (px)

Citation preview

Page 1: Vb Script Selected Notes

VB SCRIPT SELECTED NOTES:

If you want to access controls on the form when the page loads, the <SCRIPT> tag must follow the <FORM> tag; otherwise, the script attempts to reference a control that doesn't exist yet. You can retrieve the status of a CheckBox control through its Checked property, and the index of the selected item in a Select control using its SelectedIndex property. To check the state of a radio button, you use the following syntax:

If DataForm.RadioButton.Item (0). Checked Then ...

That is: If formname.radioButton.Item (index).Checked then…You frequently use VBScript code to react to events raised by controls. For example, buttons, CheckBox and RadioButton controls raise an onclick event when they're clicked

The following example uses a TextBox, one Button, and two RadioButton controls; when the push button is clicked, the code converts the TextBox's contents to uppercase or lowercase, according to the RadioButton currently selected:

<FORM NAME="DataForm"><INPUT TYPE=Text NAME="UserName" VALUE=""><BR><INPUT TYPE=Radio NAME="Case" CHECKED>Uppercase<INPUT TYPE=Radio NAME="Case">Lowercase<BR><INPUT TYPE=BUTTON NAME="Convert" VALUE="Convert"></FORM>

<SCRIPT LANGUAGE="VBScript">Sub Convert_Onclick() If DataForm.Case.Item(0).Checked Then DataForm.UserName.Value = UCase(DataForm.UserName.Value) Else DataForm.UserName.Value = LCase(DataForm.UserName.Value) End IfEnd Sub</SCRIPT>

Another way to specify which VBScript routine should execute when the user acts on a control is to add an onclick attribute in the definition of the control and set its value to reference the code that has to be executed when the control is clicked. For example, the following code defines two RadioButtons that, when clicked, modify the contents of a TextBox control:

Page 2: Vb Script Selected Notes

<FORM NAME="UserData"><INPUT TYPE=Text NAME="UserName" VALUE=""><BR><INPUT TYPE=Radio NAME="Case" onClick="Convert(0)" CHECKED>Uppercase<BR><INPUT TYPE=Radio NAME="Case" onClick="Convert(1)">Lowercase<BR></FORM>

<SCRIPT LANGUAGE="VBScript">Sub Convert(ind) If ind = 0 Then UserData.Username.Value = UCase(UserData.Username.Value) Else UserData.Username.Value = LCase(UserData.Username.Value) End IfEnd Sub</SCRIPT>

Usually, the value of the onclick attribute is the name of the procedure that must be called, together with its arguments (index, in this case), but in general it can be any valid piece of VBScript code.

TextBox, TextArea, and Select controls raise an onchange event when the user types something in them or selects a new item.

Scripts are often used to add items to a Select control at run time. The sequence of actions necessary for reaching this goal will probably seem contorted to a Visual Basic programmer: You must use the CreateElement method of the Document object, set its Text and Value properties, and finally add it to the Options collection of the Select contro

The following example creates a form with a Select control and a push button.

Initially, the Select control contains only one item, but you can add two more items by clicking on the button:

<FORM NAME="UserForm"><SELECT NAME="Countries" SIZE=1> <OPTION VALUE=1>US</OPTION><OPTION VALUE=2>US</OPTION><option value=3>kkk</></SELECT><INPUT TYPE=BUTTON NAME="AddCountries" VALUE="Add Countries"></FORM>

Page 3: Vb Script Selected Notes

<SCRIPT LANGUAGE="VBScript">Sub AddCountries_onclick() Dim e Set e = Document.createElement("OPTION") e.Text = "Italy"_ e.Value = 2 Userform.Countries.Options.Add e

Set e = Document.createElement("OPTION") e.Text = "Germany" e.Value = 3 Userform.Countries.Options.Add eEnd Sub</SCRIPT>

Generating HTML code

VBScript lets you generate a new HTML page on the fly, using the Write method of the Document object.

I explain the Document object (and all the other objects available to HTML programmers) later in this chapter, but a simple example can give you a taste of what you can do:

<FORM NAME="UserData"><INPUT TYPE=Text NAME="Rows" VALUE="10"><INPUT TYPE=Text NAME="Cols" VALUE="10"><BR><INPUT TYPE=Button NAME="Generate" VALUE="Generate Table"></FORM>

<SCRIPT LANGUAGE="VBScript">Sub Generate_onclick() Dim rows, cols ' We need to store these values in variables before the form is ' destroyed when a new document is created. Therefore,we do ‘the following rows = UserData.Rows.Value cols = UserData.Cols.Value

Document.Open Document.Write "<H1>Multiplication Table</H1>" Document.Write "<TABLE BORDER=1>" For r = 1 to rows Document.Write "<TR>" For c = 1 to cols Document.Write "<TD> " & (r*c) & " </TD>" Next Document.Write "</TR>"

Page 4: Vb Script Selected Notes

Next Document.Write "</TABLE>"End Sub</SCRIPT>

An Introduction to Dynamic HTML

Tags

You've already seen how you can use the <DIV> and </DIV> tags to group multiple elements and create a portion of the page that can be assigned a common style. For example, you can use these tags to create rectangular areas with text and background colors that are different from the other elements:

<DIV STYLE=" WIDTH=300; HEIGHT=100; COLOR=white; BACKGROUND=red;">A red block with white text<BR>Another line in the same block<br>Another one from Lactos Inc</DIV>

When you're working with DHTML, you might need to process items that are smaller than the heading or the paragraph. You can reference such items using the <SPAN> and </SPAN> pair of tags, which subdivide an element into smaller chunks so that each portion can have different attributes:

<DIV STYLE="WIDTH=300; HEIGHT=150; COLOR=white; BACKGROUND=red;">A red block with white text<BR><SPAN STYLE="COLOR=yellow">Some words in yellow,</SPAN><SPAN STYLE="COLOR=blue">Other words in blue</SPAN></DIV>

An important difference between the <DIV> tag and the <SPAN> tag is that the former always adds a carriage return after the closing </DIV> tag, which means that you can't continue to insert text on the same line. Conversely, the </SPAN> tag doesn't insert a carriage return, so, for example, the previous code snippet produces two lines of text, not three. The importance of the <DIV> and <SPAN> tags will be more evident when you see how you can use scripts to create dynamic pages.

The <BUTTON> and </BUTTON> tags allow you to add more versatile button controls on a form. While the standard <INPUT TYPE=Button> tag supports only a text caption, these new tags let you embed anything in the text, including an image:

Page 5: Vb Script Selected Notes

<BUTTON ID="Button1" STYLE="height=80; width=180">Click Here<IMG SRC="www.vb2themax.com/mylogo.gif"></BUTTON>

Dynamic HTML also adds several new attributes that you can use with certain tags. For example, the TABINDEX attribute lets you specify the tab order of controls on the page, exactly as the Visual Basic property does. The ACCESSKEY attribute works with some types of page elements to provide a hot key for easy Alt+key selection. The difference is that DHTML doesn't highlight the selected key in any way—you have to do it yourself. While this failure to highlight a selected key seems a flaw in DHTML, it actually gives you a lot of flexibility when building your user interface:

' A "Click Here" button that you click using the Alt+H key combination<BUTTON ID="Button1" ACCESSKEY="H">Click <B>H</B>ere</BUTTON>

Finally, the DISABLED attribute lets you selectively disable (and re enable) controls and other elements. You just need to remember that it works in a way opposite to the Visual Basics Enabled property:

<INPUT TYPE=Radio ID="optMusicCD" NAME="Product" DISABLED>Music CD

<SCRIPT LANGUAGE="VBScript">Sub Button1_onclick() ' Reenable the option button. optMusicCD.disabled = FalseEnd sub</SCRIPT>

To fine-tune the position and size of an item, you can strip the px characters appended to the value returned by the left, top, width and height properties. Using the posxxxx properties is usually better, however, because they return numerical values. The following example shows how you can move an element to the right:

rectangle.style.posLeft = rectangle.style.posLeft + 10

If a property isn't defined in the STYLE attribute, it returns Null. The posxxxx properties are anNOTE

Page 6: Vb Script Selected Notes

Use the style.color and style.backgroundColor properties to adjust the text and background color of any element on the page except the Document object, for which you should use the fgcolor and bgcolor properties exception to this rule because they always return numeric values.

Active Server PagesIn a nutshell, an ASP page is a document that resides on the Web server and that contains a mixture of HTML code and server-side scripts. Such scripts process requests coming from client browsers and can build a response page for that particular client, for example, by querying a database through ADO. This capability is very important, because it lets you create "dynamic" HTML pages that can be downloaded by any browser that supports plain HTML. For this reason, ASP can play a key role in Internet applications, whereas DHTML should be used only in more controlled environments—such as a company intranet—in which all clients can standardize on Internet Explorer.

Don't let the adjective "dynamic" confuse you. We're not talking about dynamic pages in the DHTML sense. The ASP technology doesn't deliver pages with animation and transition effects. Rather, with it you can create pages on the fly that are customized for each individual client. For example, you can have the server accept a request from a client, perform a query on a database, and then return the results of the query as a standard HTML table to that particular client.

ASP basics

An HTML page can contain two types of scripts: server-side scripts, which are executed on the server and contribute to creating the HTML document sent back to the browser, and client-side scripts, such as VBScript or JScript procedures executed within the client browser. The two types of scripts require different tags in an ASP page because the ASP filtering mechanism must execute server-side scripts without sending them to the browser but has to send client-side scripts to the browser without interpreting them.

You can insert a server-side script inside an ASP page in two ways. The first way is to use the <SCRIPT> tag with the RUNAT attribute, as here:

<SCRIPT LANGUAGE="VBScript" RUNAT="Server">' Add server-side VBScript code here.</SCRIPT>

You can specify either VBScript or JScript in the LANGUAGE attribute. Unlike client-side scripts, however, the default script language for ASP is VBScript, so you can safely omit the language specification. The second way to insert server-side scripts is to use the

Page 7: Vb Script Selected Notes

<% and %> delimiters. For example, the following statement assigns the current server time to the currTime variable:

<% currTime = Now() %>

I won't show ASP examples written in JScript, but for the sake of completeness, I'll show you how you can change the default script language for all server-side script fragments enclosed in the <% and %> delimiters:

<%@ LANGUAGE = JScript %>

Two types of statements can be enclosed between the script delimiters: those that execute a command and those that return a value. For statements that return a value, you must insert an equal sign (= character) immediately after the opening delimiter, as here:

<% = Now() %>

(Note that you can insert comments in statements that execute a command, but not in those that return a value.) The value returned by the VBScript expression is inserted in the HTML page exactly where the code snippet is. This means that you can (and often do) mix plain HTML text and server-side script code in the same line. For example, here is the source for a complete ASP document that displays the current date and time on the server:

<HTML><HEAD><TITLE>Your first ASP document</TITLE></HEAD><BODY><H1>Welcome to the XYZ Web server</H1>Today is <% = FormatDateTime(Now, 1) %>. <P>Current time on this server is <% = FormatDateTime(Now, 3) %>.</BODY></HTML>

You can use the <SCRIPT> tag to enclose individual statements and entire routines:

<SCRIPT RUNAT="Server">Function RunTheDice() RunTheDice = Int(Rnd * 6) + 1End Function</SCRIPT>

The routine defined in the page can be called elsewhere in the script:

<% Randomize Timer %>First die shown <% = RunTheDice %> <P>Second die shown <% = RunTheDice %>

Page 8: Vb Script Selected Notes

You can also embed a VBScript statement within <% and %> delimiters, but without the = symbol. The following example is more complex than the previous ones in that it alternates plain HTML and server-side statements:

<% h = Hour(Now)If h <= 6 Or h >= 22 Then %>Good Night<% ElseIf h <= 12 Then %>Good Morning<% ElseIf h <= 18 Then %>Good Afternoon<% Else %>Good Evening<% End If %>

Server-side VBScript programming

Server-side scripting isn't a lot different from client-side scripting, at least syntactically. The real difficulty in writing ASP code is in trying to anticipate what your script produces when IIS executes it.

The only relevant difference between regular VBScript code and server-side VBScript code is that a few statements are prohibited in the latter, most notably those statements that show a dialog box on the screen. This prohibition is understandable, though. After all, the script will be executed on an unattended server; no one will be there to click the OK button in a message box. So just stay clear of the MsgBox and InputBox statements when you're writing server-side VBScript code.

Server-side scripts support include files, that is, files that reside on the server and that are included as-is in the HTML page being generated. This is the syntax for inserting an include file:

<!-- #include file="Routines.inc " -->

The filename can be either a physical path (such as C:\Vbs\Routines.inc) and in this case can be absolute or relative to the current file, or it can be virtual, but in this case you need a slightly different syntax:

<!-- #include virtual="/Includes/Routines.inc" -->

There's no restriction on the file's extension, but it's common practice to use the .inc extension, to differentiate these files from other files on the Web site. The include file can contain virtually anything: plain text, HTML code, server-side scripts, and so on. The only restriction is that it can't contain incomplete portions of scripts, such as an opening <SCRIPT> tag without the corresponding </SCRIPT> tag.

Page 9: Vb Script Selected Notes

A typical use for include files is to make a number of constants available to your ASP scripts. But if these constants come from a type library, as all the ADO constants do, there's a better way to work: Just include the following directive at the very beginning of a page or in the Global.asa file. (For more information about this file, see the "The Global.asa file" section, later in this chapter.)

<!--METADATA TYPE="typelib" FILE="c:\program files\common files\system\ado\msado15.dll" -->

Server-side ActiveX componentsIf ASP pages were only able to run server-side scripts written in VBScript or JScript, they would hardly qualify as a viable means for writing complex Internet applications. Fortunately, you can augment the power of plain VBScript by instantiating external ActiveX components, either standard or custom ones. For example, a server-side script can query a database by instantiating an ADO Recordset object and then using its properties and methods. To create ActiveX components, you have to use the Server.CreateObject method instead of the simpler CreateObject command, but apart from this detail, you can process the returned object reference as you would in plain VBScript (or Visual Basic, for that matter). The following ASP code snippet demonstrates how you can use this capability to dynamically build a table with the results of a query on the Authors table of a copy of the Biblio.mdb database stored on the server machine: "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Biruk\main.mdb;Persist Security Info=False"

<%Dim rs, conn, sqlSet rs = Server.CreateObject("ADODB.Recordset")' Modify the next lines to match your directory structure.conn = "Provider=Microsoft.Jet.OLEDB.3.51;" conn = conn & "Data Source=c:\Microsoft Visual Studio\Vb98\Biblio.MDB"' Return all the authors whose birth year is known.sql = "SELECT * FROM Authors WHERE NOT ISNULL([Year Born])"rs.Open sql, conn %>

<H1>A query on the Authors Table</H1><TABLE WIDTH=75% BGCOLOR=LightGoldenrodYellow BORDER=1 CELLSPACING=1 CELLPADDING=1> <TR> <TH ALIGN=center>Author ID</TH> <TH>Name</TH> <TH ALIGN=Center>Year Born</TH> </TR><% Do Until rs.EOF %> <TR> <TD ALIGN=center> <%= rs("Au_Id")%> </TD> <TD> <%= rs("Author")%> </TD>

Page 10: Vb Script Selected Notes

<TD ALIGN=center> <%= rs("Year Born") %> </TD> </TR><% rs.MoveNext Loop rs.Close %></TABLE>