Form-Building Routines III—the Conclusion

f you’ve been following this series, the last couple of articles (see Resources) focused on writing some useful “form-building” routines in ASP pages. I’ll continue this month by developing routines for displaying check boxes and radio button controls. Again, like last month’s article, the focus will be on building data-bound controls.

The previous articles showed:

  • a manual way to build a form containing labels and text boxes, select controls (combo and list boxes)
  • how to automate the process by building functions that build the HTML for labels and controls
  • how to automate building data-bound controls
  • how to handle form field validation
Building Check boxes and Radio buttons.
Building check boxes and radio buttons in HTML is simple. To generate a checkbox, you use the INPUT tag with a TYPE attribute of CHECKBOX.

   

The preceding code line generates only the checkbox, the little control that you can check “on” or “off.” Place the text for the check box label after the tag:

      Please inform me via e-mail.

The VALUE attribute determines the value the form sends to the server when the user selects the checkbox. By default, checkboxes return on when they have no explicit VALUE attribute; however, using a value of “1” makes it easier to determine if the user checks the control. If the user doesn’t check the control, the form returns no value, regardless of the VALUE attribute.

Displaying a radio button is very similar. The following code displays two radio buttons that belong to the same group?that is, only one of the radio buttons in the group can be selected. You create a group by naming a set of radio buttons with the exact same name.

    Male    Female

Figure 1. Simple HTML Form: Use VALUE properties to determine checked buttons.

For a group of radio buttons, you use the VALUE property to determine which radio button was selected. Radio buttons also return “on” by default, but it’s bad design to have just one radio button on a form; therefore you should always set the VALUE property for radio buttons.

Consider the following scenario. You’re building a form that looks like Figure 1.

This simple form contains a group of radio buttons and one checkbox. In a more complex situation you might set the radio button and check box captions and values from values stored in a database.

Simple Radio Buttons and Check Boxes
For simple radio buttons and checkboxes, such as gender or yes/no questions, you generally hard-coded the captions rather than populating them from a database. . Here’s the code to generate simple radio buttons and checkboxes, like those shown in Figure 1.:

      WriteFormBegin    “frmInfo”, “pgApply.asp”, _         “POST”, “return ValidateForm(this);”      WriteTableBegin 600            DisplayTextField    “First Name:”, “first_name”, _         “first_name”, 60, 35, True         DisplayTextField    “Last Name:”, “last_name”, _         “last_name”, 60, 35, True         DisplayTextField    “Title:”, “title”, _         “title”, 60, 80, False                           DisplayRadioButtonFromArray   “Gender:”,”gender”,_         1,Array(“Male”,”Female”),False            DisplayCheckBox      “Preferences:”,”notify_me”,_         1, “Notify me via e-mail”      DisplaySubmitButton  “Submit”, “cmd”         WriteTableEnd
The new code is the call to the “DisplayRadioButtonFromArray” sub routine. For the “gender” group, you write:

   DisplayRadioButtonFromArray   “Gender:”,”gender”,_      1,Array(“Male”,”Female”),False
The code to display the checkbox using the new “DisplayCheckBox” routine is similar:

   DisplayCheckBox      “Preferences:”,”notify_me”,_      1, “Notify me via e-mail”
The DisplayRadioButtonFromArray routine accepts 5 parameters, of which the fourth is the most interesting (see Table 1).

Table 1: Parameters for the DisplayRadioButtonFromArray routine.

StrLabel The text for the label
StrFieldNameThe name of the radio button group
StrValue The index of the radio button that should be selected by default.
AryLabels An array of captions?one for each radio button in the group.
blnRequired A Boolean flag to indicate this group of radio button is a required control on the form.

I called the routine “DisplayRadioButtonFromArray” because it accepts an array of captions with a default “VALUE” property equal to the index of the array?or some multiple thereof. Here’s the code:

   Sub DisplayRadioButtonFromArray   (byval strLabel, byval strFieldName,  _      byval strValue, byval aryLabels, _      byval blnRequired)      Dim i            Response.Write “”      Response.write “”       If blnRequired Then         Response.write “”      End if      Response.Write strLabel & ” ”         Response.Write “”         For i = 0 to UBound(aryLabels)         Response.Write “” & _      aryLabels(i) & _      “
” Next Response.Write “” Response.Write “” End Sub

The Code Explained
The initial lines of code for the DisplayRadioButtonFromArray routine are identical to the DisplayTextbox routine. The routine displays two cells of a single row of a table, with the label on the left side.

         Response.Write “”      Response.write “”       If blnRequired Then         Response.write “”      End if      Response.Write strLabel & ” ”      Response.Write ““
Next, the code outputs the HTML for a group of radio buttons, using the array values passed to in the fourth (aryLabels) parameter to set the captions. You can use the VBScript function UBound to discover the maximum index of the array:

   For i = 0 to UBound(aryLabels)
For each item in the array, the loop writes the INPUT tag that produces the radio button and then writes the caption using the text in the array item.

      Response.Write “” & _         aryLabels(i) & _         “
Add a HTML line break
tag and continue with the next item in the array:

   Next
Finally, close the table cell and table row tags:

   Response.Write “”   Response.Write ““
Notice the parameters to this subroutine:

   DisplayRadioButtonFromArray   “Gender:”,”gender”,_      1,Array(“Male”,”Female”),False
The subroutine expects an array of captions. You can generate the array using the VBScript “Array” function, which returns an array from a comma-separated list of values. Alternatively, you can create an array variable, assign individual elements to the array and pass the array variable as the argument to the subroutine call.

The DisplayCheckBox Routine
The DisplayCheckBox routine uses code very similar to the DisplayTextbox routine, but outputs a checkbox. You specify the caption as the strLabel parameter.

   Sub DisplayCheckBox   (byval strLabel, _      byval strFieldName,  _      byval strValue, byval strCheckBoxLabel)      Dim i            Response.Write “”      Response.write “”       Response.Write strLabel & ” ”         Response.Write “”         Response.Write “” & _      strCheckBoxLabel          Response.Write “”      Response.Write “”               End Sub
Note that there is no “blnRequired” argument for the DisplayCheckBox routines since checkboxes cannot be marked as “required” on a form.

There are a few more enhancements possible on these routines, but I will discuss them in the next section that deal with more complicated radio buttons and checkboxes.

Data Bound Radio Buttons
Just as with the combo and listbox controls in the previous article, you can build routines that obtain the values for radio buttons. All you need to do is provide the appropriate database table and field names to the routines.

For example, if you are building a web page that presents a survey or a questionnaire and the answers for a given question are stored as records in a table, you can use the following “DisplayRadioButtonsFromDB” routine to present all the answers as radio buttons.. The routine (see Listing 1) accepts the 7 arguments shown in Table 2:

Table 2: Arguments for the DisplayRadioButtonsFromDB routine.

StrLabel The text for the label
strFieldName The name of the radio button group
strValue The index of the radio button that should be selected by default.
StrLookupTable The database table to use to find all available values for this set of radio buttons.
StrLookupID The primary key, unique id within the table, this will be assigned to the VALUE property of the radio buttons
StrLookupDesc The text of the radio button to display
blnRequired A Boolean flag to indicate this group of radio button is a required control on the form

Listing 1 contains the complete code for the DisplayRadioButtonsFromDB routine. You begin by outputting the label for the group of radio buttons:

   ‘ — Output the Label   Response.write “”    If blnRequired Then      Response.write “”   End if   Response.Write strLabel & ” ”   ‘ — Now the table cell containing all our radio buttons   Response.Write ““
The code caches the HTML for the radio buttons in an Application variable the first time it runs. Therefore, you should check to see if the output is already cached. . If it is, then you can reuse it.

      ‘ — Check the CACHE first      strResult = Application(“opt” & strFieldName)      If strResult = “” Then
If the output is not cached, you must access the database to obtain the data. There are two possible techniques: obtain the data from the database and then generate HTML text from it, or have the database return records containing pre-built HTML.

      ‘ — build your SQL statement      strSQL = “SELECT ” & strLookUpID & “,” & _         strLookUpDesc & ” FROM ” & strLookUpTable      ‘ — order by clause if needed      strSQL = strSQL & ” ORDER BY ” & strLookUpDesc      ‘ — use the SQL Statement with your standard data       ‘ — access method to obtain a recordset      ‘ — ALTERNATE TECHNIQUE TO HAVE SQL SERVER BUILD A       ‘ — LIST OF RADIO BUTTON TAGS      ‘ — USE IF NECESSARY      ‘   ‘ — build your SQL statement      ‘   strSQL = “SELECT ‘‘ + RTRIM(” & strLookUpDesc & _      “) + ‘
‘ AS TheField FROM ” & _ strLookUpTable ‘ ‘ — order by clause if needed ‘ strSQL = strSQL & ” ORDER BY ” & strLookUpDesc
Retrieve the data in a recordset (code omitted) using whatever standard technique you favor. If you’re using the first technique, iterate through the recordset building the HTML string:

      ‘ — assuming the variable objRS contains a       ‘ — valid recordset         If (objRS.BOF and objRSC.EOF) Then         strResult = “”   ‘ No records found      Else         strResult = “”         Do While Not objRS.EOF            strResult = strResult & _            “”            strResult = strResult & _               objRS(strLookUpDesc) & “
” objRS.MoveNext Loop End if ‘ if (objRSC.BOF and objRSC.EOF) Then
Notice that the code uses the same name for all radio buttons (making them part of a single group) and assigns the unique ID field (strLookUpID) to the VALUE attribute and uses the description field (strLookUpDesc) for the text of the radio buttons. End each line with a HTML break character (
) so the radio buttons appear in a vertical list.

If you use the second technique, the code is shorter because the database builds the HTML text for you.

      If (objRS.BOF and objRS.EOF) Then         strResult = “”   ‘ No records found      Else         Do While Not objRS.EOF            strResult = strResult & objRS(“theField”)            objRS.MoveNext         Loop      End if    ‘ if (objRSC.BOF and objRSC.EOF) Then
Finally, cache the generated HTML string in an application level variable so you don’t have to hit the database for every request.

   ‘ — strResult. Place it in the Application Cache    ‘ — for next go around         Application.Lock         Application(“opt” & strFieldName) = strResult         Application.UnLock 
The routine step pre-selects one of the radio buttons based on the value of the “strValue” argument sent to the routine:

      ‘ — Handle the Pre-Selection of the RADIO       ‘ — buttons control      ‘ — All we need to do is to add the word CHECKED      ‘ — next to the item whose value = strValue      strResult = Replace(strResult, “VALUE=””” & _         strValue & “”””,”VALUE=””” & strValue & _         “”” CHECKED”)
Finally, output the result:

      ‘ — Output the list of radio butotn tags      Response.write strResult      Response.Write ““
Building data bound check boxes uses an identical technique, so I’ll won’t cover it in this article.

Adding Client Side Validation
Automatically generating the client side JavaScript validation code for text boxes is relatively simple, but is slightly more complex for checking a group of radio buttons. You must iterate through the button group looking for one where the checked property is true, for example:

   var blnq5Selected = false;   for(var i in f.q5) {      if(f.q5[i].checked) {         blnq5Selected = true;      }   }   if(!blnq5Selected) {      msg += ‘Please select a value for the ‘Q5’ field.
‘; retVal = false; }
If the user neglected to select a radio button the script displays an error message.

Here’s the ASP code that generates the client side script. You should place this code at the end of the radio and check box generation routines:

   If blnRequired Then      mstrFormValidationScript = _         mstrFormValidationScript & _         “var bln” & strFieldName & _         “Selected = false;” & vbCrLf & _         “for(var i in f.” & strFieldName & _         “) {” & vbCrLf & _         ”   if(f.” & strFieldName & “[i].checked) {” & _         vbCrLf & ”      bln” & strFieldName & _         “Selected = true;” & vbCrLf & _         ”   }” & vbCrLf & “}” & vbCrLf & _         “if(!bln” & strFieldName & _         “Selected) {” & vbCrLf & _         ”   msg += ‘Please select a value for the ‘” & _         strLabel & “‘ field.
‘;” & vbCrLf & _ ” retVal = false;” & vbCrLf & _ “}” & vbCrLf & vbCrLf End if
You can download the code for all these routines from the Resources section of this article. To use the code, use an INCLUDE command to insert the file “IncFormRoutines.asp” in your ASP page:

   

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

technology leadership

Why the World Needs More Technology Leadership

As a fact, technology has touched every single aspect of our lives. And there are some technology giants in today’s world which have been frequently opined to have a strong influence on recent overall technological influence. Moreover, those tech giants have popular technology leaders leading the companies toward achieving greatness.

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job