Reputation: 323
I have a form with checkboxes that need to be processed I want to loop through each selected option but I can't seem to make ColdFusion recognize the HTML checkbox fields as a list
So if someone selected option 1 and 2 I should be able to loop through the comma separated list of submitted values . however it keep selecting the whole string as a single entry, despite the comma delimiters
Example:
<form action="" method="get">
<input name="test" type="checkbox" value="1" checked="checked" />Option1<br>
<input name="test" type="checkbox" value="2" checked="checked" />Option2<br>
<input name="test" type="checkbox" value="3" checked="checked" />Option3<br>
<input name="test" type="checkbox" value="4" checked="checked" />Option4<br>
<input name="" type="submit" />
</form>
<cfif IsDefined("test")>
<cfoutput> lenght: #len(test)#<br>
#test#
</cfoutput><br />
<cfloop index="i" list = "#test#" delimiters="," >
<cfoutput>#i# ---#test#<br /></cfoutput>
</cfloop>
</cfif>
returns:
lenght: 7
1,2,3,4
1 ---1,2,3,4
2 ---1,2,3,4
3 ---1,2,3,4
4 ---1,2,3,4
(I'm using ColdFusion 10 dev edition)
Upvotes: 1
Views: 192
Reputation: 31920
What's the problem here? Firstly the length is 7, because you're treating it as a string by using the len() function.
If however you want to find out how many list items are in it, you can use ListLen instead e.g.
length: #listlen(test)#
Secondly are you trying to get the value of each list item as you loop over it? By outputting #test#
each time you're just outputting the entire list. Instead you can simply output #i#
Upvotes: 1
Reputation: 29870
You are misreading your code. It's working:
When you reference form.test
, it will be a list of all the values you have selected in the checkboxes. EG: if you've checked them all, then the value will be 1,2,3,4
You are demonstrating this to yourself with this bit of your code:
<cfoutput>#i# ---#test#<br /></cfoutput>
You're seeing ---1,2,3,4
. IE: form.test
contains 1,2,3,4
When one loops over a list like this:
<cfloop index="i" list = "#test#" delimiters="," >
Then i
will take each element value of the list in turn. And you are also seeing this.
And the length of form.test
is indeed 7
: "1,2,3,4"
is seven chars. listLen()
would give you 4
.
Finally, some coding suggestions:
form.test
not test
isDefined()
, use structKeyExists()
i
is a poor variable name in this context (and probably confusing you), checkBoxValue
might be better. Or something that indicates what the checkbox represents.Upvotes: 8
Reputation: 1605
You are doing it correctly. You have to use variable in INDEX attribute (i in this case). If your CHECKBOXES has values of 23,12,78,56. Then I would return those values in each iteration. Look like you are being confused with "i" giving iteration counter value.
Upvotes: 2