Skip to content

Code-With-Rails/datalist-demo

Repository files navigation

f.datalist Demo

A minimal Rails app demonstrating the new f.datalist FormBuilder helper, which wires a text input to a native HTML <datalist> for autocomplete with zero JavaScript and no derived-id bookkeeping.

It's the companion code for the Code With Rails post:

Build Native Autocomplete in Rails Forms with f.datalist (No JavaScript)

f.datalist is on Rails main (slated for 8.2) but not yet in a released version, so this app's Gemfile points rails at the GitHub main branch (rails/rails#57318). Swap that for a version once 8.2 ships.

What it shows

app/views/profiles/new.html.erb has two autocomplete fields:

  • Country -- suggestions from a hardcoded list (Profile::COUNTRIES)
  • Tag -- suggestions pulled from the database (Profile.suggested_tags)

Both use the pattern from the post:

<%= f.text_field :country, list: f.field_id(:country, :datalist) %>
<%= f.datalist :country, Profile::COUNTRIES %>

The input's list: and the datalist's id are both field_id(:country, :datalist), so they stay wired together with no manual id bookkeeping.

Run it

bundle install
bin/rails db:setup   # create, migrate, and seed
bin/rails server

Then open http://localhost:3000, click into Country or Tag, and start typing -- the browser shows native suggestions with no JavaScript.

Create a few profiles with new tags, then reload the form: your tags show up in the Tag suggestion list (DB-backed choices).

Notes

  • Routes: / (new profile form), /profiles (list)
  • To reset the data: bin/rails db:reset
  • Native <datalist> dropdowns are rendered by the OS, so they show up in a real browser but not in automated screenshots.

About

Native HTML autocomplete in Rails forms with f.datalist (Rails 8.2) and zero JavaScript. Companion to codewithrails.com/blog/rails-native-autocomplete-datalist

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors