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:

14 replies on “Fixing autocomplete (autofill) on AngularJS form submit”

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 😉

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.

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

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

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…

Leave a Reply

Your email address will not be published.