I've been working with HTML on and off for a while, but somehow I managed to completely miss the idea of multi-select checkboxes until a few days ago. I've used <select> lists with the multiple attribute, but recently I came across something like this:
Example 1
Example 1
Notice that all the checkboxes share the same name attribute. Now, my first though was that this was just plain wrong. I knew that in the case of radio buttons, options were grouped by giving them the same name. But I always thought of checkboxes as isolated yes/no controls. Consequently, if I wanted to add the fruit choices above to a form, I might have done something like this:
Example 2
Checkbox inputs have the interesting beahaviour that, if they're not checked, they're simply not submitted as part of the form. In terms of ColdFusion, unchecked checkboxes are not contained in the Form struct after submission. So, in Example 2 (what I previously thought was the "right" way), let's say I check Orange, Kiwi, and Pear but leave Lime unchecked. Then I submit the form and dump the Form struct in fruitPicker.cfm. I see the following:
That works fine, but it turns out I've been doing extra work for nothing. If we use the form code in Example 1 and submit it with Orange, Kiwi and Pear checked, a dump of the form scope shows the following:
This is likely old-news to some, but if you were in the dark like me, give it a try!
NOTE: It's only the name attribute you want to make the same. Never give the same id to multiple elements on the page. It's bad for your DOM and people will laugh at you.
And in CF10, there will be a application.cfc setting that returns the list of selected checkboxes as an array.
ReplyDeleteNice. That could come in handy.
ReplyDelete