ASP beginner’s tutorial

PART FIVE

Something more useful

At some point, you may want to ask a visitor to your site for their date of birth. The non-ASP way would be to create some drop-down <select> boxes, such as:

DOB (day/month/year):
<select name="day">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>etc...</option>
</select>
<select name="month">
<option value=”1”>January</option>
<option value=”2”>February</option>
<option value=”3”>March</option>
<option value=”4”>April</option>
<option value=”5”>May</option>
<option>etc...</option>
</select>
<select name="year">
<option>1937</option>
<option>1938</option>
<option>1939</option>
<option>1940</option>
<option>1941</option>
<option>etc...</option>
</select>

View this HTML in your browser: dob.htm

As you can see, this could take some time to create by hand! Using ASP, you could create the option lists automatically! You need to a loop function to iterate through the list and output the values using the Response.Write method. We will use the simplest For … Next loop

For the day:

<select name="day">
<%
Dim i ' declare loop count variable
' output day options
For i = 1 To 31
Response.Write("<option>" & i & "</option>")
Next
%>
</select>

The new bits are:

Dim i

Whilst not strictly necessary, it is good practice to tell the server which variables you are going to use in advance. It is also good for other people reading you code to add comments using the single quote (‘). Anything after a single quote is ignored by the server.

For i = 1 To 31 … Next

This means “repeat the bit of code by increasing the value of variable i from 1 to 31 (in steps of 1)

Response.Write("<option>" & i & "</option>")

This means output the HTML tag <option>, then the value of i, the close the tag. So for a value of i=10, the HTML output would be <option>10</option>

For the month:

<select name="month">
<%
‘ output month options
For i = 1 To 12
Response.Write("<option value="& i & ">")
Response.Write(MonthName(i))
Response.Write("</option>")
Next
%>
</select>

Note that a variable only needs to be declared once and can be reused. If you declare it twice, you will get an error!

The new bit is:

MonthName(i)

This function displays the name of the month rather than just the month number, for example, MonthName(1) would result in January being displayed.

For the year:

<select name="year">
<%
' output year options
For i = 1901 To Year(Now())
Response.Write("<option>" & i & "</option>")
Next
%>
</select>

The new bit is:

For i = 1901 To Year(Now()) … Next

The counter can start at any value and this assumes a start year of 1901 and loops until the current year:

Year(Now())

Try this using the demonstration file: dob.asp

Hopefully, you will agree that this is quicker than hand coding the HTML!

 

Next: ASP and forms

Index: Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6