Mike
Mike

Reputation: 33

Knockout Observable and Google Chrome Auto-Fill issue

Basically, I have a login button on a login form that works fine with jQuery 1.8.3 (I've tried 1.9.0) and Knockout 2.2.1 observables and a binding to enable/disable the login button.

The enable button is disabled when the computed function sees that there is a missing username OR password.

However, the problem arises when Google Chrome (24.0.1312.56 m) autofills the textbox a few moments after the page loads. The viewmodel and computed observable doesn't detect when Chrome updates the textbox so the button stays disabled.

I made a basic jsfiddle. I have no clue how to make the jsfiddle autofill to show this problem :) You'll just have to trust me.

Javascript/ViewModel

$(document).ready(function(e) {
    var loginViewModel = function() {

        var self=this;
        self.loginName = ko.observable("");
        self.loginPass = ko.observable("");

        self.loginInfoValid = ko.computed(function() {

            if (self.loginName().length > 0 && self.loginPass().length > 0) {
                return true;
            } else {
                return false;
            }

        });

    };

    ko.applyBindings(new loginViewModel());     
});

HTML

<input type="text" data-bind="value: loginName, valueUpdate:'afterkeydown'"><br>
<input type="text" data-bind="value: loginPass, valueUpdate:'afterkeydown'"><br>
<span data-bind="text: loginName"></span><br>
<button data-bind="enable: loginInfoValid">Login</button>

jsfiddle: http://jsfiddle.net/vW6Xy/1/

Thank you!!

Upvotes: 3

Views: 1887

Answers (2)

Yogev Smila
Yogev Smila

Reputation: 111

Found a nice unobtrusive way of doing it, for example:

var emailInput = $('#email');
var passwordInput = $('#password');

emailInput.on('blur', function () { passwordInput.trigger('change'); });

So when you lose focus over the email/user input, it will trigger the change event on the password input causing password property on the viewmodel to be updated.

Upvotes: 1

Jeff
Jeff

Reputation: 14279

You can either

  • bind a change event handler to the text object and manually call the self.loginInfoValid method, or
  • use setTimeout to wait a short time and manually call the self.loginInfoValid method.

If the change event is thrown when Chrom autofills, that would be my preferred solution of the two.

Upvotes: 1

Related Questions