Text input elements are frequently accompanied by a label element. The label element repeats information that was supplied to the text_field helper. It would be nice if the helper could also be used to create a corresponding label. For instance:
<%= text_field "item", "description", "label" => "Description:" %>
<%= text_field "item", "description", "label_after" => "Description:" %>
would yield
<label for="item_description"> Description:</label>
<input id="item_description" name="item[description]" type="text" value="" />
<input id="item_description" name="item[description]" type="text" value="" />
<label for="item_description"> Description:</label>
Labels also make form elements easier to use by providing clickable targets. This is most useful with checkboxes because the entire label can toggle the checkbox when clicked, but it also makes text inputs easier to use by providing an alternate path to select a field.
Labels are also used by screen-reading programs for the visually impaired to give a better sense of the format of a form.
The following code can be used to accomplish this:
In application_helper.rb:
module ApplicationHelper
def check_box_with_label (object_name, method, options = {},
checked_value = "1", unchecked_value = "0")
orig = check_box(object_name, method,
options.reject {|key, value| key == :label},
checked_value, unchecked_value)
return orig << "<label for='#{options[:id]}'>#{options[:label]}</label>"
end
end
In the .rhtml:
<%= check_box_with_label
"item",
"description",
:id => "myCheckBoxId",
:label => "Description" %>
Yields:
<input id="myCheckBoxId" name="item[description]" type="checkbox" value="1" />
<input name="item[description]" type="hidden" value="0" />
<label for='myCheckBoxId'>Description</label>