tbosch / autofill-event

A polyfill to fire a change event when the browser auto fills form fields
MIT License
383 stars 51 forks source link

Fires change events when no change #2

Closed joshbmarshall closed 10 years ago

joshbmarshall commented 10 years ago

Sometimes this fires a change event even if there's no change, for example when an input field is ajax'd into the DOM

I change the triggerChangeEvent function to check if there was a previous value and match against it. I only use jQuery so it isn't going to be a straight copy-paste for you if you want it to work with angular as well.

function triggerChangeEvent(element) {
    var dochange = true;
    var value = $(element).val();
    if ($(element).attr('last-val') !== undefined) {
        if ($(element).attr('last-val') === value) {
            return;
        }
    } else {
        dochange = false;
    }
    $(element).attr('last-val', value);
    if (dochange) {
        var doc = window.document;
        var event = doc.createEvent("HTMLEvents");
        event.initEvent("change", true, true);
        element.dispatchEvent(event);
    }
}

Only issue I have had with the above code is the browser autocomplete for username and password fields, as that seems to be triggered at page load. So I do a settimeout for those particular fields.

tbosch commented 10 years ago

Hi, the only case I can think of is when an <input> has a pre existing value attribute. I fixed this with #6. Do you have any other use cases where this fires too many events?

tbosch commented 10 years ago

Closing this for now. If you have another concrete use case, please comment.

joshbmarshall commented 10 years ago

Hopefully this wont open the case again. I can confirm this is now resolved in my use case. Thank you :)