Learn how to turn our browser's default form autocompletion behavior off.
One of the greatest inventions since sliced bread is our browser's auto completion behavior where we focus on an element like input, select, textarea, or form and see a list of possible values we can select instead of writing those values manually again...like an animal:
I don’t know about you, but this simple act of our browsers remembering commonly provided information is a major timesaver. It has made the boring act of typing and re-typing names, addresses, phone numbers, and more a non-activity! Now, there will be times when the form autocomplete/autofill behavior isn’t quite what we want. Some examples of such times are when we are providing:
There are probably a boatload more examples, but the important detail is that we as developers may want to disable the autocompletion behavior our browsers provide by default. This article will show us how.
The way we can control the autocomplete behavior of an entire form or an individual input element is by using the appropriately named autocomplete attribute. A value of on for this attribute is the default behavior, and a value of off disables the autocomplete behavior.
The following is a example where we disable autocomplete on an entire form:
<form autocomplete="off" id="sumacForm"> <input type="number" min="1" required id="firstNumber"> <input type="number" min="1" required id="secondNumber"> <button type="submit">Calculate</button> </form>
If we want to disable autocomplete on just a single input element, we can scope the autocomplete attribute to just that element:
<form id="infoForm"> <input type="text" placeholder="username" required> <input type="password" placeholder="password" required> <input autocomplete="off" placeholder="2FA code" required> <button type="submit">Submit</button> </form>
<form id="infoForm"> <input type="text" placeholder="username" required> <input type="passwrod" placeholder="password" required> <input id="twoFA" type="number" placeholder="2FA code" required> <button type="submit">Submit</button> </form> <script> let twoFA = document.querySelector("#twoFA"); twoFA.setAttribute("autocomplete", "off"); </script>
What we have seen so for are a handful of ways to toggle the form autocompletion behavior on and off. To better fine-tune our autocompletion behavior, we have a bunch of values we can provide to the autocomplete attribute beyond on and off. These values like name, username, e-mail, etc. make it easier for the browser's autocompletion to display more appropriate values with some help from us. This MDN article goes into more detail on all the values you can (and probably should!) use to make your form's autocompletion behavior even better than what you may get by default from the browser.
Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!