Explain Codes LogoExplain Codes Logo

Disable autocomplete via CSS

javascript
prompt-engineering
autocomplete
browser-quirks
Alex KataevbyAlex Kataev·Jan 3, 2025
TLDR

To disable autocomplete, HTML autocomplete="off" is your best friend. This attribute can be used in both form and input tags:

<form autocomplete="off"> <input type="text" name="user"> </form>

However, not all browsers are your friends (looking at you, Internet Explorer!). Some may ignore this command due to autofill settings. To handle these uncooperative browsers, consider Javascript-based approaches or, as a last resort, browser-specific workarounds.

Dynamic control through JavaScript

JavaScript can be used to dynamically apply the autocomplete attribute, an elegant solution when working with multiple forms on a page or when forms are added via AJAX after the initial page load.

Direct application on each input

function disableAutocomplete() { document.querySelectorAll('input').forEach(input => input.setAttribute('autocomplete', 'off')); }

Run disableAutocomplete() whenever necessary. Pro tip: after dynamically adding a form, it's disableAutocomplete() o'clock.

Aiding autocomplete with unique IDs

Some browsers are stubborn. Real stubborn. You want autocomplete off, they want it on. In such cases, generating unique ids and names for your form elements can help trick these browsers. It's like putting on a fake mustache so you won't be recognized. Sneaky but effective.

Using jQuery like a boss

If you're a jQuery lover (who isn't?), you can disable autocomplete with a one-liner. But remember, with great power comes... compact, easier-to-read code.

$('input').attr('autocomplete', 'off');

Keep an eye out for specific browsers or future versions playing by their own rules. Code is a living thing, it needs care (and updates).

Edge cases and alternate solutions

Staying one step ahead of browser quirks

Autocomplete? More like auto-annoying, right? Unfortunately, a few modern browsers could still ignore your autocomplete="off" command. For these tricky situations, dummy elements or hidden fields can confuse their autofill feature, essentially giving it a red herring to chase.

Global disabling of autocomplete

Planning to go nuclear? Applying a global JavaScript solution can ensure uniformity across the webpage and cater to dynamically-loaded forms via AJAX.

Browser compatibility: Friend or foe?

Always test across different browsers because each one has a different understanding of form fields. Tools like the compatibility-checking website "Can I use..." can save you a load of stress.

Accessibility matters

Autocomplete isn't always the villain. It can be a valuable feature for users with assistive technologies. Instead of turning this off, you could ensure your form fields are properly named and labelled to make the autocomplete suggestions more effective.