Skip to main content
November 6, 2013
Answered

Count the number of values selected in a form

  • November 6, 2013
  • 3 replies
  • 8183 views

Hello

I need to count the number of values selected in a form.

Here is my form dump:

I want to count the values circled in red.

So the number I want in this case is 5.

Any suggestions?

    This topic has been closed for replies.
    Correct answer Carl Von Stetten

    Aegis,

    Yeah, good point.  Here is a minor tweak:

    <cfset total = 0>

    <cfloop collection="#FORM#" item="field">

         <cfif field NOT IS "fieldnames">

           <cfset total += ListLen( FORM[ field ] )>

         </cfif>

    </cfloop>

    <cfoutput>

         <p>Total: #total#</p>

    </cfoutput>

    -Carl V.

    3 replies

    Carl Von Stetten
    Legend
    November 6, 2013

    You get five if you count each item in the lists in the first and third form fields (ids 12053 and 12056) individually, correct?  So you need to loop over the collection and use ListLen() on the fields to count the items in each field (assuming that commas are always used to separate list items).  So this should work:

    <cfset total = 0>

    <cfloop collection="#FORM#" item="field">

         <cfset total += ListLen( FORM[ field ] )>

    </cfloop>

    <cfoutput>

         <p>Total: #total#</p>

    </cfoutput>

    -Carl V.

    Inspiring
    November 6, 2013

    Of course, doesn't CF throw in some extra fields into the FORM scope (FIELDNAMES) etc?  I would assume we would have to factor that one out of the results.

    Carl Von Stetten
    Carl Von StettenCorrect answer
    Legend
    November 6, 2013

    Aegis,

    Yeah, good point.  Here is a minor tweak:

    <cfset total = 0>

    <cfloop collection="#FORM#" item="field">

         <cfif field NOT IS "fieldnames">

           <cfset total += ListLen( FORM[ field ] )>

         </cfif>

    </cfloop>

    <cfoutput>

         <p>Total: #total#</p>

    </cfoutput>

    -Carl V.

    Inspiring
    November 6, 2013

    <cfset total = 0 />

    <cfloop collection="#FORM#" item="field">

         <cfif FORM[ field ] neq ''><cfset total += 1 /></cfif>

    </cfloop>

    <p>Total: #total#</p>

    EddieLotter
    Inspiring
    November 6, 2013

    pjunkie wrote:

    I need to count the number of values selected in a form.

    I want to count the values circled in red.

    So the number I want in this case is 5.

    5? I only see 3 circles.

    Try this:

    nCount = 0;

    For(sFormVar in Form) {

       If (Form[sFormVar] != "" )

          nCount++;

    }

    WriteDump(var=nCount, label="Number of values provided");