How to defeat autocompletion in forms
Problem
You serve up your HTML form with default values provided for each element, but some browsers overwrite these values with ones they stored from a previous visit.Solution
The simple answer is to add a nonstandard attribute called 'autocomplete' to your form element, as follows:<form autocomplete="off" ...> ... </form>Sadly this has three problems:
- Not all browsers honour it
- Values stored from a visit prior to setting this attribute will still be recalled
- The document is no longer valid html
window.onload = function() {
// loop through all the forms setting autocomplete to off unless otherwise specified
for (var i=0; i<document.forms.length; i++) {
if (document.forms[i].autocomplete == null) {
document.forms[i].autocomplete = 'off';
}
}
// setup a timer to check the forms after autocompletion has run
window.setTimeout('undoAutocompletes()', 1);
};
function undoAutocompletes() {
for (var i=0; i<document.forms.length; i++) {
var f = document.forms[i];
if (f.autocomplete=='off') {
f.reset();
}
}
}
A WebTip by Dan Boresjo
