I've been using formtastic in order to generate HTML forms on rails applications. My question, however, is really HTML-related.
Today I found a strange behaviour on the way formtastic generates checkboxes (fields of type :boolean
on formtastic lingo).
The rest of the fields (non-checkboxes) are generated this way:
<li>
<label for="my_textbox_field">My TextBox</label>
<input id="my_textbox_field" type="text" ... >
</li>
Checkboxes, however, are enclosed inside their <label>
tags completely - like this:
<li>
<label for="my_boolean_field">
<input id="my_boolean_field" type="checkbox" ... >
This is my boolean field
</label>
</li>
Formtastic philosophy seems to be based on the Learning to Love Forms presentation. In effect, on slide 36 of that presentation this structure is suggested for checkboxes. I guess in the presentation itself the presenter explained why this was done, but it is not written on the slides.
Can anyone tell me why enclosing checkboxes inside their <label>
tag might be a good idea, as opposed to putting them outside, like with textboxes?
The common UI for a text input is either a label on the left:
Email address: [____________________]
Or the label above the input:
Email address:
[___________________________________]
For a checkbox however, the common UI is for the label to appear after the input, like this:
[x] Accept terms and conditions
For the first two cases, it drastically simplifies the CSS you have to create if the label comes before the input in the markup. One could argue that the label could wrap around the input still, but the important thing here is that the text comes before the input.
In the third example (the checkbox), the text comes after the label, and again, the CSS is greatly simplified by putting the label in the right place in the markup order (after the input).
So, the checkboxes were always going to be different to the rest of the inputs. In regards to the wrapping of the checkbox with a label, this was just a personal preference, although I'd argue that since the checkbox inputs are different, having the input inside the label makes it easier to target these inputs for styling with CSS, because the markup is different.