Apr
17

IE Autocomplete Doesn't Fire onchange Event Handler

posted on 17 April 2010 in programming with 0 Comments

Warning: Please consider that this post is over 7 years old and the content may no longer be relevant.

While testing an ASP validation control in Internet Explorer I found that the validation wasn’t triggered if I selected an item from the autocomplete list for a text box, this was the same in Safari for Windows, but worked fine in Mozilla Firefox. What?!

IE form autocomplete feature

Turns out that when selecting an item from the autocomplete list the onchange event handler doesn’t fire, therefore the validation scripts don’t fire. The onblur event does fire however, meaning we can do a check to see if the data has changed and if so, manually fire the onchange event handler.

/*
Author:     Paul Heasley
Date:       15.04.2010
Version:    0.1
Description:
IE and safari do not trigger the onchange events for textboxes when using autocomplete,
so validation events don't trigger. The blur event does trigger however so this script
checks to see if the value has changed (by saving the value on focus) and manually
calling onchange.
*/
function onChangeFix() {
    var previousValue = [];
    // Get all input elements
    var inputs = document.getElementsByTagName('input');

    for (var i = 0; i < inputs.length; i++) {
        var elt = inputs[i];

        // Only update text boxes. Depending on your application you
        // may also need to fix text areas.
        if (elt.type.toLowerCase() == "text")
        {
            // Save old value.
            addEvent(elt, 'focus', function() {
                previousValue[this] = this.value;
            });

            // Compare to old value, do we need to trigger an onchange event?
            addEvent(elt, 'blur', function() {
                if (previousValue[this] != this.value)
                {
                    if (this.onchange)
                        this.onchange();
                }
            });

            // Set old value = new value to stop the blur event triggering
            // another onchange.
            addEvent(elt, 'change', function() {
                previousValue[this] = this.value;
            });
        }
    }
}

Alternatively, you can disable the autocomplete feature by adding the attrribute autocomplete="off" for either a specific input or for the entire form.

<form id="theForm" name="theForm" method="post" autocomplete="off">

Download the entire code sample including the addEvent() function.

Download source