Skip to content

Instantly share code, notes, and snippets.

@dinnouti
Created October 15, 2012 22:59
Show Gist options
  • Save dinnouti/3896201 to your computer and use it in GitHub Desktop.
Save dinnouti/3896201 to your computer and use it in GitHub Desktop.
Typeahead / Autocomplete with Twitter Bootstrap, Rails, simple_form
<%= f.input :nome, :collection => get_schools_name, :include_blank => false, :input_html => {:rel => 'autocomplete', :data_default => @school.nome} %>
$ ->
$('select[rel="autocomplete"]').each ->
option = []
$(this).find('option').each ->
option.push $(this).text()
input = $('<input>')
input.attr('type','text')
input.attr('name', $(this).attr('name') )
input.attr('id', $(this).attr('id') )
input.attr('class', $(this).attr('class') )
input.attr('data-provide', 'typeahead' )
input.val($(this).attr('data_default'))
$(this).replaceWith(input)
$(input).typeahead({
source: option
});
def get_schools_name
School.uniq.pluck(:nome)
end
@Imranshaikh
Copy link

Lots of thanks.

@qmclaugh
Copy link

Nice! Thanks.

@dannyvanhoof
Copy link

Great and simple solution!

Works equally well in combination with form_tag:

<%= select_tag "nome", options_for_select(get_schools_name), class: 'select optional', :include_blank => false, :rel => 'autocomplete', :data_default => @school.nome} %>

@despo
Copy link

despo commented Aug 12, 2013

Nice. What version are you using? I had to change source: option to local:option to get it to work with the latest typeahead.

@fadeojo
Copy link

fadeojo commented Oct 20, 2013

I tried using your solution but "typeahead" isn't working and I have bootstrap 3. can anyone help?

@jasonm23
Copy link

jasonm23 commented Nov 6, 2013

Did a similar thing with :

= f.input :CountryCode,
    label: "Country Code",
    input_html: { rel: 'autocomplete', data_default: @location[:CountryCode], autocomplete: "off", data: {source: get_country_codes, provide: "typeahead" } }

No JS/Coffee is required, Just a helper method to supply data-source with an array.

(Forgive the weird field names, the project is hanging off a legacy database.)

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