AarCee
AarCee

Reputation: 863

Jquery ui autocomplete not working with rails 4.2

I'm working on a Rails 4.2 app (with Bootstrap) and trying to set up autocomplete in a text field. I'm following the Railscasts autocomplete association episode:

My application.js looks like:

//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require turbolinks

and my application.css contains:

 *
 *= require_tree .
 *= require_self
 *= require jquery-ui
 */

The model "modelname" contains a text field "email". In the view file new.html.erb for modelname I have:

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@modelname) do |f| %>
    <%= f.label "EmailId" %>
    <%= f.text_field :email %>
    <%= f.submit "Create", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

In the app\assets\javascripts\modelnames.coffee file I've added the autocomplete source:

jQuery ->
    $('#modelname_email').autocomplete
        source: ['abc', 'def', 'ade', 'dge', 'ghi']

But as I start typing in the "modelname_email" text field the autocomplete doesn't show up.

Have I missed any required step?

EDIT: I've also read that Turbolinks sometimes causes issues with respect to jquery, could that be the cause here? I tried some changes but they had no effect.

Upvotes: 0

Views: 1396

Answers (2)

AarCee
AarCee

Reputation: 863

I couldn't get jquery-ui's autocomplete to work so I used the rails4-autocomplete gem and it's worked so far.

Following are the steps I followed:

  1. In the gemfile, add the following entry:

    gem 'rails4-autocomplete'

  2. In app\assets\javascripts\application.js, add the following entry (I added it before the "//= require turbolinks" entry):

    //= require autocomplete-rails

  3. In config\routes.rb (model name is "employee" and it's field on which I require autocomplete is "email" ):

    resources :employees do
        get :autocomplete_employee_email, :on => :collection
    end
    
  4. In the employees\new.html.erb (this contains the text field for "email" where I require the autocomplete to work) (Please see comment for the code):

  5. And finally in the app\controllers\employees_controller.erb:

    def autocomplete_employee_email

    term = params[:term]

    if term && !term.empty?

    items = Employeee.select("distinct email"). where("LOWER(email) like ?", term.downcase + '%'). limit(10).order(:email)

    else

    items = {}

    end

    render :json => json_for_autocomplete(items, :email)

    end

Upvotes: 1

MarsAtomic
MarsAtomic

Reputation: 10673

JQuery needs to be listed prior to require_tree in your manifests.

application.css

 *
 *= require_self
 *= require jquery-ui
 *= require_tree .
 */

application.js

//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require turbolinks
//= require_tree .

Upvotes: 0

Related Questions