VBScript Tutorial

VBScript Tutorial #5

So far we've been using standard script that could be used with the Windows Scripting Host (WSH) that comes as standard with Windows 98/2000. Now I'll show you how to communicate with the browser. Take a look at this:-

<script language="VBS">
document.write "Hello"
</script>


Note first that you can call the script language using a shorter name rather than VBScript if you wish although VBS is less descriptive. This simple script will display the word Hello. Now look at this script:-

<script language="VBS">
document.write "Hello"
document.write "there!"
next
</script>

Before you run it, try to predict what will happen. Now run it. Ypu might have expected the second document.write function to print on a new line but it doesn't. To make it do so you need to use this:-

<script language="VBS">
document.write "Hello<BR>"
document.write "there!"
</script>

Now this is interesting. We have used some HTML code and embedded it in the string but the browser has interpreted it as HTML (provided you used the <HTML> tag as in previous tutorials). So perhaps you can see how scripts and HTML are interlinked. Still doesn't look quite as hoped as there is no space between the two words. Adding a space between Hello and the BReak tag will do the trick. So what else can we do?

<script language="VBS">
for i = 1 to 3
document.write "Hello "
document.write "<b>there!</b><BR>"
next
</script>

This will then write Hello there! three times but the there! will be in bold again due to the <b> bold HTML tags. For all you old BASIC programmers, also note that there isn't a next i statement but simply a next. This I agree is a very bad programming style but it is the only form that VBScript will take. Loops can still be nested but will have to be indented to make the flow more readable (good practice anyway but I can't show it here as HTML won't let me). Now for the final bit of code this session:-

<script language="VBS">
dim name
name="Nick"

for i = 1 to 3
document.write "Hello "
document.write "<b>" & name & "</b><BR>"
next
</script>


We have DIMensioned a variable and assigned a name (mine in this case but it could be yours) which we use further down. Note how we use the & (ampersand) to display the contents of the varibable otherwise you'll get the word name printed on the screen. Note also the break is used otherwise we won't get a nice display in on new lines. That's it for today. I hope you can see that scripting is a very powerful addition to the HTML armoury and I'll be delving deeper in future tutorials.

Back

Written by Nick Cheesman. Last updated: 01/04/2004
Please eMail me at:
nickjc@nickjc.co.uk if you need help