Joe Wang
Joe Wang

Reputation: 21

simple_form radio button (need to add <span> tag inside of <label>

What is the best way to create the following HTML using simple_form_for gem?

<label>
   <input name="form-field-radio" type="radio" />
   **<span class="lbl"> radio option 2</span>**
</label>

Note that by default when I create a radio buttons using the following statements, the above is not created. How can I add that tag in?

<%= f.input :state, :collection => Project::STATES, :as => :radio_buttons %>

Upvotes: 2

Views: 1219

Answers (1)

krsyoung
krsyoung

Reputation: 1241

I had a similar need (to embed a <span> within the <label>). It isn't the cleanest solution but it did work and I think with some tweaking it could get you the ability to have your input and span embedded within the label. The following modification results in:

<label>Name: 
  <span class="hint">this is a hint...</span>
</label>

I added the following as an initializer (using rails 4 and simple_form 3) to override the label_text method:

# initializers/simple_form_custom.rb
module SimpleForm
  module Components
    module Labels

      def label_text
        if hint
          hint_text = %[<span class="hint">#{hint}</span>]
        else
          hint_text = ""
        end
        SimpleForm.label_text.call(raw_label_text, required_label_text, hint_text).strip.html_safe
      end

    end
  end
end

Then in initializers/simple_form.rb I have:

config.label_text = lambda { |label, required, hint| "#{label}: #{required} #{hint}" }

Upvotes: 1

Related Questions