Skip to content

Instantly share code, notes, and snippets.

@brunopgalvao
Last active December 23, 2022 02:32
Show Gist options
  • Save brunopgalvao/6d86e8e2c570f86823ea to your computer and use it in GitHub Desktop.
Save brunopgalvao/6d86e8e2c570f86823ea to your computer and use it in GitHub Desktop.
HTML5 Datalist using Ruby on Rails form_for
<%= form_for @person do |f| %>
<%= f.label :first_name, "First Name" %>:
<%= f.text_field :first_name, list: 'first-name' %>
<datalist id="first-name">
<% Person.all.each do |person| %>
<option value="<%= person.first_name %>"></option>
<% end %>
</datalist>
<%= f.submit %>
<% end %>
You may also want to do distinct:
<% Person.select(:first_name).distinct.each do |person| %>
@philiplambok
Copy link

Thank you!

@joleb
Copy link

joleb commented Apr 5, 2019

better use

datalist#first-name
  = options_for_select(Person.pluck(:first_name).uniq, @person.first_name)

It is written in Slim but you get the idea ;)
It's way more compact and easier to read imo.

@ThreeMangoTrees
Copy link

How can we test the view that results from the datalist options. For e.g. in case we have following 4 options ---

       1. fruit/apple
       2. fruit/guava
       3. fruit/melon
       4. fruit/grapes

and I select fruit/apple in the text_field, the list under the text_filed will also show fruit/apple. How to write an rspec test that verifies that the list under the text_field is showing fruit/apple ? This is just to validate that the datalist is working.

@yshmarov
Copy link

yshmarov commented Nov 26, 2021

Very good! Thanks @brunopgalvao @joleb

@zhlotia
Copy link

zhlotia commented Nov 28, 2021

Thanks for this @brunopgalvao!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment