Programming blog by Ezekiel Victor

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:

14 Comments

  1. jdallard /

    Hello,

    I was having issues with this solution : Every two or three refresh of my chrome browser i had the error “Object [object Object] has no method ‘submit'”

    I replaced this :
    elem.unbind(‘submit’).submit(function(e) {

    with this :
    elem.unbind(‘submit’).bind(‘submit’, function(e) {

    and it seems to work.

    Hope that helps anyone who run into the same problem 😉

  2. Thx for this piece of code.

    I’ve also needed to switch from .submit to bind(‘submit’)

    I also needed to reduce arguments in find function to ‘input’ only.

  3. Stuart R /

    In jqlite (if you aren’t using jquery) this changes things a little:

    elem.find(‘input’).triggerHandler(‘change’)

  4. sam records /

    Worked like a charm – thanks.

  5. Thanks. Works better than tbosch’s autofill-event plugin.

  6. amit b /

    Using Firefox 30.0
    had to add event ‘.trigger(‘blur’)’ to make it work, else the form was getting submitted empty, and then the model was getting filled. Don’t know the exact reason why…

  7. Hi!

    Thanks for good solution.

    For me it works with native $timeout;

  8. Wagner /

    Try to use ng-required=”true”
    instead
    ng-required

    Its work for me

Leave a Reply

Solve this equation to prove you're human:
Time limit is exhausted. Please reload CAPTCHA.