Checkboxes come in useful when you have several choices that can be selected. For instance, if you had a form that asked a user what kind of computer they owned, they could select more than one computer.
How to use checkboxes
Using checkboxes are simple. The one thing you got to remember is checkboxes are a group, which means they all must have the same name, however, different values.
|<form action=”myform_pro.asp” name=”myform” action=”post”>
What type of computer do you have?<br>
Dell<input type=”checkbox” name=”computer” value=”dell”><BR>
GateWay<input type=”checkbox” name=”computer” value=”GateWay”><BR>
Apple<input type=”checkbox” name=”computer” value=”apple”><BR>
The first line of code starts our form and gives it the value of myform. The action property is set at post so no information is past through the browser address bar (querystring). The action property tells our browser where to take the information once the form is submitted so the information can be processed.
We then create a checkbox using the input tag. As you can see, every checkbox has the same name but a different value. Why? We give the checkboxes the same name so we know they are from the same group.
Our last lines of code submits and closes our form.
So what happens once the form is submitted? It goes to myform_pro.asp. Now, in order to retrieve what checkboxes where clicked, you can use the following code:
The code above will retrieve for you what checkboxes were clicked. If all checkboxes were clicked, you would see the following:
dell, gateway, apple
Now you know what checkboxes where clicked, however, it’s one string. This could be a problem if you wanted to store each option separately for polling reasons. With ASP, there’s a solution. It’s the VBScript Split() function.
|choices = Request.Form(“computer”)
choices = Split(choices, “,”)
For Each member in choices
Response.Write member & “<BR>”
At first this might seem a little overwhelming, but let me assure you it’s nothing special. Let me explain each line of code to you.
The first line of code retrieves the values from the form.
The second line of code uses the VBScript Split() function to split the values from our comma-delimted string. For instance, when the Split() function finds a comma, it stops, makes the following word it’s own string and then starts again until it finds another comma and so on…
So what happens to all of our new string of words? Well they are actually an array of strings and in order to retrieve those values from an array, we must use a For…Next Loop. This brings us to our last lines of code.
A For…Next Loop is used to iterate through each member of a group and that’s what we use to retrieve our values.
Now since you have those values from our form, you can store them in a database or redirect the user to a page that sells Dell computers, etc.