简体   繁体   中英

Call a function if browser autofills an input field

I'm trying to invoke a function that detects whether the browser has autofilled a field, and if so, add a class to it.

I found a thread with a solution that works partially: https://stackoverflow.com/a/25393087

Here's my integration of it:

$.fn.allchange = function (callback) {
    var me = this;
    var last = "";
    var infunc = function () {
        var text = $(me).val();
        if (text != last) {
            last = text;
            callback();
        }
        setTimeout(infunc, 10);
    }
    setTimeout(infunc, 10);
};

$(".input").allchange(function () {
    $('.input').addClass('not--empty');
});

The problem I'm having is that I also have a function that checks for a change to the input on blur and also adds a class to that input. However, the above function is causing it to be added to all instances of '.input'.

I think the solution would be to invoke the function on only the autofilled element, but when I run the function below, it doesn't work:

$(".input").allchange(function () {
    $(this).addClass('not--empty');
});

Any ideas how to get this working?

EDIT: Thought I'd add an image to clarify what I'm referring to:

在此处输入图片说明

So this actually turned out to be a very simple solution – and it may not work for all browsers, but it works flawlessly for Chrome/Firefox/Safari latest, which for this application is fine.

setTimeout(function() {
    $('.input:-webkit-autofill').each(function() {
        var elem = $(this);
        $(elem).addClass('not--empty');
    })
},100);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM