Zulhilmi Zainudin
Zulhilmi Zainudin

Reputation: 9355

How to add data attribute in Rails form select tag?

I found this Bootstrap Select project and its gem for Rails. I want to implement search in the select tag.

I do inspect element and here is the HTML source:

<select class="selectpicker" data-live-search="true">
  <option>Hot Dog, Fries and a Soda</option>
  <option>Burger, Shake and a Smile</option>
  <option>Sugar, Spice and all things nice</option>
</select>

How do I add data-live-search="true" inside my form select tag?

My form select:

<%= f.select :food_id, options_for_select(Food.all.map{|c| [c.name, c.id]}, f.object.food_id), {}, {class: "form-control selectpicker"} %>

What I've tried:

<%= f.select :food_id, options_for_select(Food.all.map{|c| [c.name, c.id]}, f.object.food_id), {}, {class: "form-control selectpicker", data: "live-search"} %>

But it's not working.

Upvotes: 25

Views: 25245

Answers (4)

Dorian
Dorian

Reputation: 9085

if you are passing a block to the select, you need to pass {} two times, e.g.

    => f.select :to_user_id, {}, {}, data: { placeholder: "Choisis des invités..." }, class: "chosen-image" do
      - User.find_each do |user|
        option(data-img-src="#{user_image_url_for(user)}" value="#{user.id}")
          = user.first_name

Upvotes: 1

gilcierweb
gilcierweb

Reputation: 2714

  <%= f.select(:plan_id, {},{}, {'v-model'=>"plan_id",'@change'=>"onChange", class: "form-control"}) do  %>
<% Plan.all.each do |plan| %>
    <%= content_tag(:option,"#{plan.name.upcase} #{plan.max_items}  #{number_to_currency(plan.price)}", value:plan.id, :data => {items: plan.max_items, price: plan.price}) %>
<% end%>
<% end%>

Upvotes: 4

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

Try:

{class: "form-control selectpicker", "data-live-search" => "true" }

Upvotes: 35

un_gars_la_cour
un_gars_la_cour

Reputation: 269

<%= f.select :food_id, options_for_select(Food.all.map{|c| [c.name, c.id]}, f.object.food_id), {}, {class: "form-control selectpicker", data: {"live-search": true}} %>

Upvotes: 25

Related Questions