Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails helper "Collection Select"

I have the exact same problem as this guy , since no one has answered, I decided to repost:

I have been trying to implement this jquery plugin to my app.I need help trying to output something like this

<select name="user[university_id]" id="user_university_id" class="selectable">
<option value="1" title="uni1">Uni1</option>
<option value="2" title="uni2">Uni2</option>
</select>

by using a rails helper...the problem is the helpers never seem to output a title attribute to the option tags.. which is critical for this plugin

please help, thanks in advance

Edit: my current rails code is

<%= f.collection_select(:university_id,University.all,:id,:name)%

which simply outputs

<select name="user[university_id]" id="user_university_id">
        <option value="1">Uni1</option>
        <option value="2">Uni2</option>
    </select>

So basically what I need is a way to also add title attribute to my options.

like image 893
jalagrange Avatar asked Mar 21 '26 09:03

jalagrange


1 Answers

Have you thought about rolling your own helper? I just copied this code out of the rails source and then changed the name and added the title.

  def options_for_select_with_title(container, selected = nil)
    return container if String === container

    container = container.to_a if Hash === container
    selected, disabled = extract_selected_and_disabled(selected)

    options_for_select = container.inject([]) do |options, element|
      text, value = option_text_and_value(element)
      selected_attribute = ' selected="selected"' if option_value_selected?(value, selected)
      disabled_attribute = ' disabled="disabled"' if disabled && option_value_selected?(value, disabled)
      options << %(<option title="#{html_escape(value.to_s.downcase)}" value="#{html_escape(value.to_s)}"#{selected_attribute}#{disabled_attribute}>#{html_escape(text.to_s)}</option>)
    end

    options_for_select.join("\n").html_safe
  end
like image 100
Geoff Lanotte Avatar answered Mar 23 '26 00:03

Geoff Lanotte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!