Browser Autofill and Javascript triggered events

时光总嘲笑我的痴心妄想 提交于 2019-11-27 17:34:46

问题


One of our users just brought up the fact that their browsers Autofill doesn't cause JS onChange events to fire; this causes a problem with user registration for us.

Is this by design? Is there a way to work around it?


回答1:


One solution I have been using occasionally is to check whether the value of the field/input/select differs from it's defaultValue. defaultValue would be the value that was originally in the markup, and value is the current value aka selected or entered value. This would probably differ even though the form was autopopulated.

If you want to turn off autofill altogether, it might be wise to add autocomplete="off" on fields that are directly connected to your logic.




回答2:


If you want to get the autofill behaviour but change the styling, maybe you can do something like this (jQuery):

$(window).load(function(){  
  if($('input:-webkit-autofill')){   
    $('input:-webkit-autofill').each(function(){
      //put your conditions here 
    });   
    // RE-INITIALIZE VARIABLES HERE IF YOU SET JQUERY OBJECT'S TO VAR FOR FASTER PROCESSING 
}});



回答3:


Have you tried using the onpropertychanged instead of onchange event? That's for IE only though and is the recommended fix on MSDN.




回答4:


Just in case someone is still looking for a solution (just as I was today), to listen to a browser autofill change, here's a custom jquery method that I've built, just to simplify the proccess when adding a change listener to an input:

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

You can call it like this:

$("#myInput").allchange(function () {
    alert("change!");
});



回答5:


Here's a pretty good solution that does something similar to what jishi described:

https://web.archive.org/web/20131125153914/http://furrybrains.com/2009/01/02/capturing-autofill-as-a-change-event/

Updated the broken link with Wayback Machine link



来源:https://stackoverflow.com/questions/4938242/browser-autofill-and-javascript-triggered-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!