Categories
AngularJS

Fixing autocomplete (autofill) on AngularJS form submit

Many browsers support autocomplete but do not trigger “change” events on inputs when the user initiates autocomplete. This is a problem for many libraries and code in the wild that rely on performing some action (e.g. input validation) when input data change.

With respect to AngularJS forms, the problem becomes obvious if you are using AngularJS form validation. If you autofill an empty form then press Submit, AngularJS will think the inputs are still empty:

AngularJS unaware of autofilled inputs
AngularJS unaware of autofilled inputs

Here is a simple login form subject to this issue:

Unfortunately the underlying issue of not having an appropriate event related to autofill must be addressed by browser vendors. However in the meantime, we can use a custom directive to ensure AngularJS knows about form changes made by autofill at time of form submit.

Patch directive

In CoffeeScript

In JavaScript

Directive in use

The directive is simple to use; just apply it to your form and away you go:

Categories
Twitter Bootstrap

How to use rich objects and typed objects with Bootstrap Typeahead

The JS components of Twitter Bootstrap are somewhat lacking in functionality when compared to well established plugins that do the same things (autocompletes, tooltips, etc.). However, I still use them on Bootstrap projects just because it is nice to have homogeneous interfaces to things—and, of course, it is easy then to jump on other Bootstrap projects and be in familiar territory right off the bat.

One of the continuing problems I face is with Bootstrap Typeahead, in particular its lack of native support for non-String items. I constantly come across this; rare is it that one can identify an item in a list by that item’s user-friendly string representation, i.e. more often than not you need to be working with a fully typed thing, not just a string.

Other autocompletes and typeaheads support rich objects out of the box but Typeahead needs a little massaging—fortunately not much, and not anything requiring changes to the core. Here is a sample showing a Typeahead that uses a rich UsState class (a natural extension to the Twitter demo using string state names):

Bootstrap Typeahead only gets tripped up with rich object sources for the updater method namely. The key component here is ensuring your class has a toString() method that serializes instances correctly, as well as a fromString() static method to deserialize. For my purposes I include the popular json2.js for JSON.stringify() and JSON.parse():

Then, in your Typeahead updater:

Note that Typeahead passes the stringified object, which we deserialize, and expects a string return to stuff into the text input.

And because I love CoffeeScript so much, here is the same demo in CS: