Simple necessity, but clearly no easy way to do it with Simple Form.
I need to put a span
before each radio input
in a Rails form that uses Simple form. I've successfully added a span
to a text input as stated in this guidelines, but I cannot make out how to do the same thing with radio buttons (as well as check boxes).
I don't want to use jQuery, which I am currently using as a workaround.
UPDATE 1
As @TarynEast asked in a comment, I tried creating an initializer with the following code I've been able to prepend a span
tag to a string input
.
Initializer
# config/initializers/simple_form__spanner
class SpannerInput < SimpleForm::Inputs::Base
def input(wrapper_options)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
spanner_input = "<span></span>"
spanner_input << @builder.text_field(attribute_name,merged_input_options)
return spanner_input.html_safe
end
end
View
# the view code
<%= ff.input :xxx, label: 'XXX', as: :spanner %>
HTML Output
# the output in view
<div class="form-group spanner optional xxx">
<div class="control-label-wrap">
<label class="control-label spanner optional" for="xxx_1">XXX</label>
</div>
<span></span>
<input class="form-control spanner optional" type="text" value="some value" name="xxx[1]" id="xxx_1">
</div>
Now I'd love to be able to do the same with radio buttons and checkboxes. The output should be something like:
<label><span></span><input ... ></label>
<label><span></span><input ... ></label>
<label><span></span><input ... ></label>
UPDATE 2
(almost a solution)
I have something that can somehow do what I want, i.e. having a span
per input in a collection of radio buttons or checkboxes. It outputs the span after the input
tag, but before the text so it kinda works.
The solution doens't make use of any initializer, it's just a lambda that runs for every object in the collection.
Assuming you have an array which called choices
:
choices = [
{ label: "Foo", value: "foo" },
{ label: "Bar", value: "bar" }
]
View
# the view code
<%= ff.input :xxx,
collection: choices,
label_method: -> (choice){ "<span></span>#{ choice[:label] }".html_safe } %>
Output
<label><input ... ><span></span> Foo </label>
<label><input ... ><span></span> Bar </label>