TheRanch
TheRanch

Reputation: 23

cfloop through dynamic form fields

I have a form that allows the user to add co-authors so I'm trying to loop through those fields (if they exist) but can't seem to be able to get the values. "coauthorNo" is a hidden input field that only exists if the user adds 1 or more co-authors. I'm testing with a cfoutput in my page to see if I can get the values but no luck thus far. This is running on a Coldfusion 10 server.

<cfif IsDefined("FORM.coauthorNo")>    
  <cfset coAuthCount = listLen("#FORM.coauthorNo#", ",")>

            <cfloop from="0" to="#coAuthCount#" index="i">
                <cfset CoAuthF = "#FORM['CoAuthFirstName'&i]#">
                <cfset CoAuthL = "#FORM['CoAuthLastName'&i]#">

                <cfoutput>CoAuth's: #CoAuthF#, #CoAuthL#,</cfoutput>
            </cfloop>
</cfif>

Edit: Changed the cfloop from value to 1 and that fixed it. My dynamically created form fields started at 1 vs 0. ie CoAuthFirstName1

Upvotes: 2

Views: 2268

Answers (1)

Mark A Kruger
Mark A Kruger

Reputation: 7193

FYI there's no need for all this rigamarole. You can loop through a list easily.

<Cfset lCount = 0/>    
<cfif IsDefined("FORM.coauthorNo")>    

                <cfloop list="#form.coauthorNo#" index="i">
                    <cfset CoAuthF = FORM['CoAuthFirstName' & lCount]>
                    <cfset CoAuthL = FORM['CoAuthLastName' & lCount]>

                    <cfoutput>CoAuth's: #CoAuthF#, #CoAuthL#,</cfoutput>
                    <Cfset lCount++/>
                </cfloop>
    </cfif>

And get in the habit of excluding the pound signs when you are not outputting stuff to the page or passing an attribute to a tag like cfloop. It makes for cleaner code.

Upvotes: 2

Related Questions