Rails and JQuery autocomplete

My last post was for adding a tokeninput field to form that could be dynamically updated, but I’ve kinda used them inappropriately, for single-value text boxes.

So I got brave and decided to have a go at implementing the JQuery autocomplete widget to replace a slightly unwieldy and inflexible select list.

This time the Gemfile needs to include a bit more,

# Use jquery as the JavaScript library
gem 'jquery-rails'
gem 'jquery-ui-rails', '~> 4.0'
gem 'jquery-modal-rails'
gem 'jquery-tokeninput-rails'

(I have left in the modal and tokeninput items used elsewhere). Notice that I have fixed the jquery-ui-rails to version 4. This is because version 5 is out and that’s seriously incompatible with a lot of existing JQuery gems; I did experiment with using V5 (or jquery.ui.rails or something like that) but there was no way I could get any of the ui elements working. All my other RoR sites are based around v4 and I’m determined to maintain a consistent platform across the applications.

(I’m also using turbolinks – not sure why – and that seems to have its own problems with JQuery)

The general methodology with the route, controller action, JSON template are the same as before,but this time the JQuery call is,

$( "#phone_ext_number" ).autocomplete({source: '/phones/'+$("#phone_sub_department_id option:selected").val()+'/extension_list.json'});

With the _form partial containing,

<%= f.text_field :ext_number, {:size => 6, "data-pre" => Extension.select(:extension).where(id: @phone.extension_id).map(&:extension).to_json, :class => "phonebook"} %>

This is so much better than an auto-populated select list, because the data to be inputted falls within well-defined ranges and known beforehand. It’s easy to type in for the user, but the autocomplete only lists extensions not already assigned and uses the entered digits to further constrain the list, from which a user is free to select. It also means I can do a fair bit of data validation to prevent bad data going in; this application is replacing a legacy website that is notorious for inaccurate records and we’re working on the principle of making it harder to submit bad data, but easy to enter good stuff.

I’m quite pleased with the result and will use the autocomplete elsewhere, replacing some of the wayward tokeninput laziness.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s