Support datalist HTML element

In order to generate an HTML datalist element with Rails I needed the following code:

<%= content_tag(:datalist, nil, id: :payees_datalist, 'data-autocomplete-input-target' => :datalist) do %>
  <% @payees.each do |payee| %>
    <%=
      content_tag(
        :option,
        nil,
        value: payee.name,
        data: { id: payee.id },
        'data-autocomplete-input-target' => 'datalistOption'
      )
    %>
  <% end %>
<% end %>

It would be great to have a simple way to do that. Something like the following code:

datalist_tag(:payee_datalist, @payees.map { # ... }, optional_html_options)
4 Likes

I’ve created the PR #52137.

1 Like

I’m trying to implement this in Rails 8. Specifically,I’m replacing awesomplete with straight HTML 5.0 using datalist.

I have the datalist generated by a partial that new/edit uses:

<%= tag.datalist( options_for_select(Client.order(:city).distinct.pluck(:city).take(10)), id: “client-cities-list”) %>

That generates a very nice set of options:


<datalist id="client-cities-list"><option value=""></option>
<option value="Albany">Albany</option>
<option value="Astoria">Astoria</option>
<option value="Auburn">Auburn</option>
<option value="Bayonne">Bayonne</option>
<option value="Bellvue">Bellvue</option>
<option value="Bethlehem">Bethlehem</option>
<option value="Binghamton">Binghamton</option>
<option value="boston">boston</option>
<option value="Bronx">Bronx</option></datalist>

Note that city is not a table/relationship to Client. It’s just a text field.

If I ‘hardcode’ the html in the form like: <input list="client-cities-list" id="ice-man-choice" name="ice-man-choice" type="text">

THAT input works; that is, for example, as I type “Albany” the A’s pop up.

When I use the tag: <%= f.text_field :city, list: “client-cities-list” %>

It generates: <input list="client-cities-list" type="text" name="client[city]" id="client_city">

BUT there is no “dropdown” effect, it’s just a text field with no functionality, even though is much the same as the hardcoded html above, except for the id and name, which have something to do with the problem, but I’m not concerned about what happens when I submit, the issue is the datalist isn’t being engaged to show possible selectoins. I don’t see any javascript issues. There are no events attached to either field, and I see nothing happening in the console with I select and type either one of the fields.

What is my face palming stupidity here?

Thanks!