[thelist] CF Radio Buttons Tip

Joshua OIson joshua at alphashop.net
Thu Mar 22 12:30:44 CST 2001


----- Original Message -----
From: "matthew garrett" <matthew.garrett at snet.net>
Subject: Re: [thelist] CF Radio Buttons Tip

> Before I post this as a tip, how would you improve it?
>
> <cfset answers = '#one#, #two#, #three#, #four#, #five#, #six#, #seven#,
> #eight#, #nine#, #ten#'>
> <cfset key = 'a,b,c,d,e,a,b,c,d,e'>
> <cfset correct="0">
> <cfset loopcount="1">
> <cfloop index="current" list="#answers#">
>   <cfoutput>
>     <cfif trim(current) IS '#trim(listGetAt(key, loopcount))#'>
>         <p>Right you are! Question #loopcount# is #listGetAt(key,
> loopcount)#.</p>
>         <cfset correct = '#incrementValue(correct)#'>
>     <cfelse>
>         <p>Hey, you got this one wrong. Question #loopcount# is actually
> #listGetAt(key, loopcount)#, not #current#.</p>
>     </cfif>
>     <cfset loopcount = '#incrementValue(loopcount)#'>
>   </cfoutput>
> </cfloop>
>
> <cfoutput>
>     <p>You got this many right: #correct#</p>
> </cfoutput>

A couple things might help this code.  For starters, I would not name the
radio buttons with text names such as "one", "two", "three".  I would change
the names to "question1", "question2", etc.

Then I would change the code to this:

<cfset key = "a,b,c,d,e,a,b,c,d,e">

<cfset j = "0">
<cfset correct = "0">
<cfloop index="i" list="#key#">
  <cfset j = j + 1>
  <cfparam name="form.question#j#" default="">
  <cfset answer = form["question" & j]>
  <cfif answer IS i>
    <p>Right you are! Question #j# is #i#.</p>
    <cfset correct = correct +1'>
  <cfelse>
    <p>Hey, you got this one wrong. Question #j# is actually #i#, not
#answer#.</p>
  </cfif>
</cfloop>

<cfoutput>
  <p>You got this many right: #correct#</p>
</cfoutput>

One of the benefits of this code is that it correctly handles the case when
no answer for a question was selected.

You may also notice that I am using the alternate for of Structure indexing
when I call form["name"].  You may find that using this format may simplify
code.  But note, this method of accessing a structure as if it was an array
was introduced in a newer version of CF (4.5?)

Good luck,

-joshua





More information about the thelist mailing list