How do you disable browser autocomplete on web form field / input tags?

Viewed 1332338

How do you disable autocomplete in the major browsers for a specific input (or form field)?

99 Answers

Firefox 30 ignores autocomplete="off" for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following commentary from May 5, 2014:

  • The password manager always prompts if it wants to save a password. Passwords are not saved without permission from the user.
  • We are the third browser to implement this change, after IE and Chrome.

According to the Mozilla Developer Network documentation, the Boolean form element attribute autocomplete prevents form data from being cached in older browsers.

<input type="text" name="foo" autocomplete="off" />

In addition to setting autocomplete=off, you could also have your form field names be randomized by the code that generates the page, perhaps by adding some session-specific string to the end of the names.

When the form is submitted, you can strip that part off before processing them on the server-side. This would prevent the web browser from finding context for your field and also might help prevent XSRF attacks because an attacker wouldn't be able to guess the field names for a form submission.

<form name="form1" id="form1" method="post"
      autocomplete="off" action="http://www.example.com/form.cgi">

This will work in Internet Explorer and Mozilla Firefox. The downside is that it is not XHTML standard.

As others have said, the answer is autocomplete="off".

However, I think it's worth stating why it's a good idea to use this in certain cases as some answers to this and duplicate questions have suggested it's better not to turn it off.

Stopping browsers storing credit card numbers shouldn't be left to users. Too many users won't even realize it's a problem.

It's particularly important to turn it off on fields for credit card security codes. As this page states:

"Never store the security code ... its value depends on the presumption that the only way to supply it is to read it from the physical credit card, proving that the person supplying it actually holds the card."

The problem is, if it's a public computer (cyber cafe, library, etc.), it's then easy for other users to steal your card details, and even on your own machine a malicious website could steal autocomplete data.

Always working solution

I've solved the endless fight with Google Chrome with the use of random characters. When you always render autocomplete with random string, it will never remember anything.

<input name="name" type="text" autocomplete="rutjfkde">

Hope that it will help to other people.

Update 2022:

Chrome made this improvement: autocomplete="new-password" which will solve it but I am not sure, if Chrome change it again to different functionality after some time.

On a related or actually, on the completely opposite note -

"If you're the user of the aforementioned form and want to re-enable the autocomplete functionality, use the 'remember password' bookmarklet from this bookmarklets page. It removes all autocomplete="off" attributes from all forms on the page. Keep fighting the good fight!"

In addition to

autocomplete="off"

Use

readonly onfocus="this.removeAttribute('readonly');"

for the inputs that you do not want them to remember form data (username, password, etc.) as shown below:

<input type="text" name="UserName" autocomplete="off" readonly 
    onfocus="this.removeAttribute('readonly');" >

<input type="password" name="Password" autocomplete="off" readonly 
    onfocus="this.removeAttribute('readonly');" >

Hope this helps.

Just set autocomplete="off". There is a very good reason for doing this: You want to provide your own autocomplete functionality!

We did actually use sasb's idea for one site.

It was a medical software web app to run a doctor's office. However, many of our clients were surgeons who used lots of different workstations, including semi-public terminals. So, they wanted to make sure that a doctor who doesn't understand the implication of auto-saved passwords or isn't paying attention can't accidentally leave their login information easily accessible.

Of course, this was before the idea of private browsing that is starting to be featured in Internet Explorer 8, Firefox 3.1, etc. Even so, many physicians are forced to use old school browsers in hospitals with IT that won't change.

So, we had the login page generate random field names that would only work for that post. Yes, it's less convenient, but it's just hitting the user over the head about not storing login information on public terminals.

Use a non-standard name and id for the fields, so rather than "name" have "name_". Browsers will then not see it as being the name field.

The best part about it is that you can do this to some, but not all, fields and it will autocomplete some, but not all fields.

Adding the

autocomplete="off"

to the form tag will disable the browser autocomplete (what was previously typed into that field) from all input fields within that particular form.

Tested on:

  • Firefox 3.5, 4 BETA
  • Internet Explorer 8
  • Chrome

In order to avoid the invalid XHTML, you can set this attribute using JavaScript. An example using jQuery:

<input type="text" class="noAutoComplete" ... />

$(function() {
    $('.noAutoComplete').attr('autocomplete', 'off');
});

The problem is that users without JavaScript will get the autocomplete functionality.

Things had changed now as I tried it myself old answers no longer work.

Implementation that I'm sure it will work. I test this in Chrome, Edge and Firefox and it does do the trick. You may also try this and tell us your experience.

set the autocomplete attribute of the password input element to "new-password"

<form autocomplete="off">
....other element
<input type="password" autocomplete="new-password"/>
</form>

This is according to MDN

If you are defining a user management page where a user can specify a new password for another person, and therefore you want to prevent autofilling of password fields, you can use autocomplete="new-password"

This is a hint, which browsers are not required to comply with. However modern browsers have stopped autofilling <input> elements with autocomplete="new-password" for this very reason.

Here's the perfect solution that will work in all browsers as of May 2021!

TL;DR

Rename your input field names and field ids to something non-related like 'data_input_field_1'. Then add the &#8204; character into the middle of your labels. This is a non-printing character, so you won't see it, but it tricks the browser into not recognizing the field as one needing auto-completing, thus no built-in auto-complete widget is shown!

The Details

Almost all browsers use a combination of the field's name, id, placeholder, and label to determine if the field belongs to a group of address fields that could benefit from auto-completion. So if you have a field like <input type="text" id="address" name="street_address"> pretty much all browsers will interpret the field as being an address field. As such the browser will display its built-in auto-completion widget. The dream would be that using the attribute autocomplete="off" would work, unfortunately, most browsers nowadays don't obey the request.

So we need to use some trickery to get the browsers to not display the built-in autocomplete widget. The way we will do that is by fooling the browser into believing that the field is not an address field at all.

Start by renaming the id and the name attributes to something that won't give away that you're dealing with address-related data. So rather than using <input type="text" id="city-input" name="city">, use something like this instead <input type="text" id="input-field-3" name="data_input_field_3">. The browser doesn't know what data_input_field_3 represents. But you do.

If possible, don't use placeholder text as most browsers will also take that into account. If you have to use placeholder text, then you'll have to get creative and make sure you're not using any words relating to the address parameter itself (like City). Using something like Enter location can do the trick.

The final parameter is the label attached to the field. However, if you're like me, you probably want to keep the label intact and display recognizable fields to your users like "Address", "City", "State", "Country". Well, great news: you can! The best way to achieve that is to insert a Zero-Width Non-Joiner Character, &#8204;, as the second character in the label. So replacing <label>City</label> with <label>C&#8204;ity</label>. This is a non-printing character, so your users will see City, but the browser will be tricked into seeing C ity and not recognize the field!

Mission accomplished! If all went well, the browser should not display the built-in address auto-completion widget on those fields anymore!

Google Chrome ignores the autocomplete="off" attribute for certain inputs, including password inputs and common inputs detected by name.

For example, if you have an input with name address, then Chrome will provide autofill suggestions from addresses entered on other sites, even if you tell it not to:

<input type="string" name="address" autocomplete="off">

If you don't want Chrome to do that, then you can rename or namespace the form field's name:

<input type="string" name="mysite_addr" autocomplete="off">

If you don't mind autocompleting values which were previously entered on your site, then you can leave autocomplete enabled. Namespacing the field name should be enough to prevent values remembered from other sites from appearing.

<input type="string" name="mysite_addr" autocomplete="on">

I tried almost all the answers, but the new version of Chrome is smart; if you write

autocomplete="randomstring" or autocomplete="rutjfkde"

it automatically converts it to

autocomplete="off"

when the input control receives the focus.

So, I did it using jQuery, and my solution is as follows.

$("input[type=text], input[type=number], input[type=email], input[type=password]").focus(function (e) {
    $(this).attr("autocomplete", "new-password");
})

This is the easiest and will do the trick for any number of controls you have on the form.

<input autocomplete="off" aria-invalid="false" aria-haspopup="false" spellcheck="false" />

i find it works for me on all browsers. When I make use of only the autocomplete it doesn't work except i combine all the attributes that you see. Also i got the solution from google form input field

To solve this problem, I have used some CSS tricks and the following works for me.

input {
    text-security:disc;
    -webkit-text-security:disc;
    -mox-text-security:disc;
}

Please read this article for further detail.

To prevent browser auto fill with the user's saved site login credentials, place a text and password input field at the top of the form with non empty values and style "position: absolute; top: -999px; left:-999px" set to hide the fields.

<form>
  <input type="text" name="username_X" value="-" tabindex="-1" aria-hidden="true" style="position: absolute; top: -999px; left:-999px" />
  <input type="password" name="password_X" value="-" tabindex="-1" aria-hidden="true" style="position: absolute; top: -999px; left:-999px" />
  <!-- Place the form elements below here. -->
</form>

It is important that a text field precede the password field. Otherwise the auto fill may not be prevented in some cases.

It is important that the value of both the text and password fields not be empty, to prevent default values from being overwritten in some cases.

It is important that these two fields are before the "real" password type field(s) in the form.

For newer browsers that are html 5.3 compliant the autocomplete attribute value "new-password" should work.

<form>
  <input type="text" name="username" value="" />
  <input type="password" name="password" value="" autocomplete="new-password" />
</form>

A combination of the two methods can be used to support both older and newer browsers.

<form>
  <div style="display:none">
    <input type="text" readonly tabindex="-1" />
    <input type="password" readonly tabindex="-1" />
  </div>
  <!-- Place the form elements below here. -->
  <input type="text" name="username" value="" />
  <input type="password" name="password" value="" autocomplete="new-password" />
</form>

If you want to prevent the common browser plug-in LastPass from auto-filling a field as well, you can add the attribute data-lpignore="true" added to the other suggestions on this thread. Note that this doesn't only apply to password fields.

<input type="text" autocomplete="false" data-lpignore="true" />

I was trying to do this same thing a while back, and was stumped because none of the suggestions I found worked for me. Turned out it was LastPass.

Most of the answers didn't help as the browser was simply ignoring them. (Some of them were not cross-browser compatible). The fix that worked for me is:

<form autocomplete="off">
    <input type="text" autocomplete="new-password" />
    <input type="password" autocomplete="new-password" />
</form>

I set autofill="off" on the form tag and autofill="new-password" wherever the autofill was not necessary.

Easy Hack

Make input read-only

<input type="text" name="name" readonly="readonly">

Remove read-only after timeout

$(function() {
    setTimeout(function() {
        $('input[name="name"]').prop('readonly', false);
    }, 50);
});

As of Dec 2019:

Before answering this question let me say, I tried almost all the answers here on SO and from different forums but couldn't find a solution that works for all modern browsers and IE11.

So here is the solution I found, and I believe it's not yet discussed or mentioned in this post.

According to Mozilla Dev Network(MDN) post about how to turn off form autocomplete

By default, browsers remember information that the user submits through fields on websites. This enables the browser to offer autocompletion (that is, suggest possible completions for fields that the user has started typing in) or autofill (that is, pre-populate certain fields upon load)

On same article they discussed the usage of autocmplete property and its limitation. As we know, not all browsers honor this attribute as we desire.

Solution

So at the end of the article they shared a solution that works for all browsers including IE11+Edge. It is basically a jQuery plugin that do the trick. Here is the link to jQuery plugin and how it works.

Code snippet:

$(document).ready(function () {        
    $('#frmLogin').disableAutoFill({
        passwordField: '.password'
    });
});

Point to notice in HTML is that password field is of type text and password class is applied to identify that field:

<input id="Password" name="Password" type="text" class="form-control password">

Hope this would help someone.

There are many answers but most of them are hacks or some kind of workaround.

There are three cases here.

Case I: If this is your standard login form. Turning it off by any means is probably bad. Think hard if you really need to do it. Users are accustomed to browsers remembering and storing the passwords. You shouldn't change that standard behaviour in most cases.

In case you still want to do it, see Case III

Case II: When this is not your regular login form but name or id attribute of inputs is not "like" email, login, username, user_name, password.

Use

<input type="text" name="yoda" autocomplete="off">

Case III: When this is not your regular login form but name or id attribute of inputs is "like" email, login, username, user_name, password.

For example: login, abc_login, password, some_password, password_field.

All browsers come with password management features offering to remember them OR suggesting stronger passwords. That's how they do it.

However, suppose you are an admin of a site and can create users and set their passwords. In this case you wouldn't want browsers to offer these features.

In such cases, autocomplete="off" will not work. Use autocomplete="new-password"

<input type="text" name="yoda" autocomplete="new-password">

Helpful Link:

  1. https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion

To disable the autocomplete of text in forms, use the autocomplete attribute of and elements. You'll need the "off" value of this attribute.

This can be done in a for a complete form or for specific elements:

  1. Add autocomplete="off" onto the element to disable autocomplete for the entire form.
  2. Add autocomplete="off" for a specific element of the form.

form

<form action="#" method="GET" autocomplete="off">
</form>

input

<input type="text" name="Name" placeholder="First Name" autocomplete="off">

A workaround is not to insert the password field into the DOM before the user wants to change the password. This may be applicable in certain cases:

In our system we have a password field which in an admin page, so we must avoid inadvertently setting other users' passwords. The form has an extra checkbox that will toggle the password field visibility for this reason.

So in this case, autofill from a password manager becomes a double problem, because the input won't even be visible to the user.

The solution was to have the checkbox trigger whether the password field is inserted in the DOM, not just its visibility.

Pseudo implementation for AngularJS:

<input type="checkbox" ng-model="createPassword">
<input ng-if="changePassword" type="password">

I wanted something that took the field management completely out of the browser's hands, so to speak. In this example, there's a single standard text input field to capture a password — no email, user name, etc...

<input id='input_password' type='text' autocomplete='off' autofocus>

There's a variable named "input", set to be an empty string...

var input = "";

The field events are monitored by jQuery...

  1. On focus, the field content and the associated "input" variable are always cleared.
  2. On keypress, any alphanumeric character, as well as some defined symbols, are appended to the "input" variable, and the field input is replaced with a bullet character. Additionally, when the Enter key is pressed, and the typed characters (stored in the "input" variable) are sent to the server via Ajax. (See "Server Details" below.)
  3. On keyup, the Home, End, and Arrow keys cause the "input" variable and field values to be flushed. (I could have gotten fancy with arrow navigation and the focus event, and used .selectionStart to figure out where the user had clicked or was navigating, but it's not worth the effort for a password field.) Additionally, pressing the Backspace key truncates both the variable and field content accordingly.

$("#input_password").off().on("focus", function(event) {
    $(this).val("");
    input = "";

}).on("keypress", function(event) {
    event.preventDefault();

    if (event.key !== "Enter" && event.key.match(/^[0-9a-z!@#\$%&*-_]/)) {
        $(this).val( $(this).val() + "•" );
        input += event.key;
    }
    else if (event.key == "Enter") {
        var params = {};
        params.password = input;

        $.post(SERVER_URL, params, function(data, status, ajax) {
            location.reload();
        });
    }

}).on("keyup", function(event) {
    var navigationKeys = ["Home", "End", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"];
    if ($.inArray(event.key, navigationKeys) > -1) {
        event.preventDefault();
        $(this).val("");
        input = "";
    }
    else if (event.key == "Backspace") {
        var length = $(this).val().length - 1 > 0 ? $(this).val().length : 0;
        input = input.substring(0, length);
    }
});

Front-End Summary

In essence, this gives the browser nothing useful to capture. Even if it overrides the autocomplete setting, and/or presents a dropdown with previously entered values, all it has is bullets stored for the field value.


Server Details (optional reading)

As shown above, JavaScript executes location.reload() as soon as the server returns a JSON response. (This logon technique is for access to a restricted administration tool. Some of the overkill, related to the cookie content, could be skipped for a more generalized implementation.) Here are the details:

  • When a user navigates to the site, the server looks for a legitimate cookie.
  • If there isn't any cookie, the logon page is presented. When the user enters a password and it is sent via Ajax, the server confirms the password and also checks to see if the user's IP address is in an Authorized IP address list.
  • If either the password or IP address are not recognized, the server doesn't generate a cookie, so when the page reloads, the user sees the same logon page.
  • If both the password and IP address are recognized, the server generates a cookie that has a ten-minute life span, and it also stores two scrambled values that correspond with the time-frame and IP address.
  • When the page reloads, the server finds the cookie and verifies that the scrambled values are correct (i.e., that the time-frame corresponds with the cookie's date and that the IP address is the same).
  • The process of authenticating and updating the cookie is repeated every time the user interacts with the server, whether they are logging in, displaying data, or updating a record.
  • If at all times the cookie's values are correct, the server presents the full website (if the user is logging in) or fulfills whatever display or update request was submitted.
  • If at any time the cookie's values are not correct, the server removes the current cookie which then, upon reload, causes the logon page to be redisplayed.

Unfortunately, this option was removed in most browsers, so it is not possible to disable the password hint.

Until today, I did not find a good solution to work around this problem. What we have left now is to hope that one day this option will come back.

I went through the same problem, today 09/10/2019 only solution I found was this

Add autocomplete="off" into the form tag.

put 1 false inputs after opening form tag.

<input id="username" style="display:none" type="text" name="fakeusernameremembered">

but it won't work on password type field, try

<input type="text" oninput="turnOnPasswordStyle()" placeholder="Enter Password" name="password" id="password" required>

on script

function turnOnPasswordStyle() {
    $('#password').attr('type', "password");
}

This is tested on Chrome-78, IE-44, Firefox-69

The autofill functionality changes the value without selecting the field. We could use that in our state management to ignore state changes before the select event.

An example in React:

import React, {Component} from 'react';

class NoAutoFillInput extends Component{

    constructor() {
        super();
        this.state = {
            locked: true
        }
    }

    onChange(event){
        if (!this.state.locked){
            this.props.onChange(event.target.value);
        }
    }

    render() {
        let props = {...this.props, ...{onChange: this.onChange.bind(this)}, ...{onSelect: () => this.setState({locked: false})}};
        return <input {...props}/>;
    }
}

export default NoAutoFillInput;

If the browser tries to fill the field, the element is still locked and the state is not affected. Now you can just replace the input field with a NoAutoFillInput component to prevent autofill:

<div className="form-group row">
    <div className="col-sm-2">
        <NoAutoFillInput type="text" name="myUserName" className="form-control" placeholder="Username" value={this.state.userName} onChange={value => this.setState({userName: value})}/>
    </div>
    <div className="col-sm-2">
        <NoAutoFillInput type="password" name="myPassword" className="form-control" placeholder="Password" value={this.state.password} onChange={value => this.setState({password: value})}/>
    </div>
</div>

Of course, this idea could be used with other JavaScript frameworks as well.

None of the solutions I've found at this day bring a real working response.

Solutions with an autocomplete attribute do not work.

So, this is what I wrote for myself:

<input type="text" name="UserName" onkeyup="if (this.value.length > 0) this.setAttribute('type', 'password'); else this.setAttribute('type', 'text');" >

You should do this for every input field you want as a password type on your page.

And this works.

cheers

Pretty sure this is the most generic solution as of today

This stops auto-complete and the popup suggestion box too.

Intro

Let's face it, autocomplete=off or new-password doesn't seem to work. It's should do but it doesn't and every week we discover something else has changed and the browser is filling a form out with more random garbage we don't want. I've discovered a really simple solution that doesn't need autocomplete on sign in pages.

How to implement

Step 1). Add the same function call to the onmousedown and onkeyup attributes for your username and password fields, making sure you give them an id AND note the code at the end of the function call. md=mousedown and ku=keyup

For the username field only add a value of &nbsp; as this prevents the form auto-filling on entry to the page.

For example:

<input type="text" value="&nbsp;" id="myusername" onmousedown="protectMe(this,'md')" onkeyup="protectMe(this,'ku')" />

Step 2). Include this function on the page

function protectMe(el,action){

 // Remove the white space we injected on startup
 var v = el.value.trim();
 
// Ignore this reset process if we are typing content in
// and only acknowledge a keypress when it's the last Delete
// we do resulting in the form value being empty
 if(action=='ku' && v != ''){return;} 

// Fix double quote issue (in the form input) that results from writing the outerHTML back to itself
  v = v.replace(/"/g,'\\"'); 
  
  // Reset the popup appearing when the form came into focus from a click  by rewriting it back
  el.outerHTML=el.outerHTML; 

  // Issue instruction to refocus it again, insert the value that existed before we reset it and then select the content.
  setTimeout("var d=document.getElementById('"+el.id+"'); d.value=\""+v+"\";d.focus();if(d.value.length>1){d.select();}",100);
}

What does it do?

  • Firstly it adds an &nbsp; space to the field so the browser tries to find details related to that but doesn't find anything, so that's auto-complete fixed
  • Secondly, when you click, the HTML is created again, cancelling out the popup and then the value is added back selected.
  • Finally, when you delete the string with the Delete button the popup usually ends up appearing again but the keyup check repeats the process if we hit that point.

What are the issues?

  • Clicking to select a character is a problem but for a sign in page most will forgive the fact it select all the text
  • Javascript does trim any inputs of blank spaces but you might want to do it too on the server side to be safe

Can it be better?

Yes probably. This is just something I tested and it satisfies my basic need but there might be more tricks to add or a better way to apply all of this.

Tested browsers

Tested and working on latest Chrome, Firefox, Edge as of this post date

I must have spent two days on this discussion before resorting to creating my own solution:

First, if it works for the task, ditch the input and use a textarea. To my knowledge, autofill/autocomplete has no business in a textarea, which is a great start in terms of what we're trying to achieve. Now you just have to change some of the default behaviors of that element to make it act like an input.

Next, you'll want to keep any long entries on the same line, like an input, and you'll want the textarea to scroll along the y-axis with the cursor. We also want to get rid of the resize box, since we're doing our best to mimic the behavior of an input, which doesn't come with a resize handle. We achieve all of this with some quick CSS:

#your-textarea {
  resize: none;
  overflow-y: hidden;
  white-space: nowrap;
}

Finally, you'll want to make sure the pesky scrollbar doesn't arrive to wreck the party (for those particularly long entries), so make sure your text-area doesn't show it:

#your-textarea::-webkit-scrollbar {
  display: none;
}

Easy peasy. We've had zero autocomplete issues with this solution.

(It works in 2021 for Chrome (v88, 89, 90), Firefox, Brave, and Safari.)

The old answers already written here will work with trial and error, but most of them don't link to any official documentation or what Chrome has to say on this matter.

The issue mentioned in the question is because of Chrome's autofill feature, and here is Chrome's stance on it in this bug link - Issue 468153: autocomplete=off is ignored on non-login INPUT elements, Comment 160

To put it simply, there are two cases -

  • [CASE 1]: Your input type is something other than password. In this case, the solution is simple, and has three steps.

  • Add the name attribute to input

  • name should not start with a value like email or username. Otherwise Chrome still ends up showing the dropdown. For example, name="emailToDelete" shows the dropdown, but name="to-delete-email" doesn't. The same applies for the autocomplete attribute.

  • Add the autocomplete attribute, and add a value which is meaningful for you, like new-field-name

It will look like this, and you won't see the autofill for this input again for the rest of your life -

  <input type="text/number/something-other-than-password" name="x-field-1" autocomplete="new-field-1" />
  • [CASE 2]: input type is password
  • Well, in this case, irrespective of your trials, Chrome will show you the dropdown to manage passwords / use an already existing password. Firefox will also do something similar, and same will be the case with all other major browsers. 2
  • In this case, if you really want to stop the user from seeing the dropdown to manage passwords / see a securely generated password, you will have to play around with JS to switch input type, as mentioned in the other answers of this question.

2 Detailed MDN documentation on turning off autocompletion - How to turn off form autocompletion

None of the provided answers worked on all the browsers I tested. Building on already provided answers, this is what I ended up with, (tested) on Chrome 61, Microsoft Edge 40 (EdgeHTML 15), IE 11, Firefox 57, Opera 49 and Safari 5.1. It is wacky as a result of many trials; however it does work for me.

<form autocomplete="off">
    ...
    <input type="password" readonly autocomplete="off" id="Password" name="Password" onblur="this.setAttribute('readonly');" onfocus="this.removeAttribute('readonly');" onfocusin="this.removeAttribute('readonly');" onfocusout="this.setAttribute('readonly');" />
    ...
</form> 

<script type="text/javascript">
    $(function () {           
        $('input#Password').val('');
        $('input#Password').on('focus', function () {
        if (!$(this).val() || $(this).val().length < 2) {
            $(this).attr('type', 'text');
        }
        else {
            $(this).attr('type', 'password');
        }
    });
    $('input#Password').on('keyup', function () {
        if (!$(this).val() || $(this).val().length < 2) {
            $(this).attr('type', 'text');
        }
        else {
            $(this).attr('type', 'password');
        }
    });
    $('input#Password').on('keydown', function () {
        if (!$(this).val() || $(this).val().length < 2) {
            $(this).attr('type', 'text');
        }
        else {
            $(this).attr('type', 'password');
        }
    });
</script>

Fixed. Just need to add above real input field

https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion - MDN https://medium.com/paul-jaworski/turning-off-autocomplete-in-chrome-ee3ff8ef0908 - medium tested on EDGE, Chrome(latest v63), Firefox Quantum (57.0.4 64-бит), Firefox(52.2.0) fake fields are a workaround for chrome/opera autofill getting the wrong fields

 const fakeInputStyle = {opacity: 0, float: 'left', border: 'none', height: '0', width: '0'}

 <input type="password" name='fake-password' autoComplete='new-password' tabIndex='-1' style={fakeInputSyle} />

<TextField
  name='userName'
  autoComplete='nope'
  ... 
/>

<TextField
      name='password'
      autoComplete='new-password'
      ... 
    />

I was able to stop Chrome 66 from autofilling by adding two fake inputs and giving them position absolute:

<form style="position: relative">
  <div style="position: absolute; top: -999px; left: -999px;">
    <input name="username" type="text" />
    <input name="password" type="password" />
  </div>
  <input name="username" type="text" />
  <input name="password" type="password" />

At first, I tried adding display:none; to the inputs but Chrome ignored them and autofilled the visible ones.

This worked for me like a charm.

  1. Set the autocomplete attribute of the form to off
  2. Add a dummy input field and set its attribute also to off.
<form autocomplete="off">
 <input type="text" autocomplete="off" style="display:none">
</form>

I'v solved putting this code after page load:

<script>
var randomicAtomic = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
  $('input[type=text]').attr('autocomplete',randomicAtomic);
</script>

The simplest answer is

<input autocomplete="on|off">

But keep in mind the browser support. Currently, autocomplete attribute is supported by

Chrome 17.0 & latest IE 5.0 & latest
Firefox 4.0 & latest
Safari 5.2 & latest
Opera 9.6 & latest

My solution with jQuery. It may not be 100% reliable, but it works for me. The idea is described in code annotations.

    /**
 * Prevent fields autofill for fields.
 * When focusing on a text field with autocomplete (with values: "off", "none", "false") we replace the value with a new and unique one (here it is - "off-forced-[TIMESTAMP]"),
 * the browser does not find this type of autocomplete in the saved values and does not offer options.
 * Then, to prevent the entered text from being saved in the browser for a our new unique autocomplete, we replace it with the one set earlier when the field loses focus or when user press Enter key.
 * @type {{init: *}}
 */
var PreventFieldsAutofill = (function () {
    function init () {
        events.onPageStart();
    }

    var events = {
        onPageStart: function () {
            $(document).on('focus', 'input[autocomplete="off"], input[autocomplete="none"], input[autocomplete="false"]', function () {
                methods.replaceAttrs($(this));
            });
            $(document).on('blur', 'input[data-prev-autocomplete]', function () {
                methods.returnAttrs($(this));
            });
            $(document).on('keydown', 'input[data-prev-autocomplete]', function (event) {
                if (event.keyCode == 13 || event.which == 13) {
                    methods.returnAttrs($(this));
                }
            });
            $(document).on('submit', 'form', function () {
                $(this).find('input[data-prev-autocomplete]').each(function () {
                    methods.returnAttrs($(this));
                });
            });
        }
    };

    var methods = {
        /**
         * Replace value of autocomplete and name attribute for unique and save the original value to new data attributes
         * @param $input
         */
        replaceAttrs: function ($input) {
            var randomString = 'off-forced-' + Date.now();
            $input.attr('data-prev-autocomplete', $input.attr('autocomplete'));
            $input.attr('autocomplete', randomString);
            if ($input.attr('name')) {
                $input.attr('data-prev-name', $input.attr('name'));
                $input.attr('name', randomString);
            }
        },
        /**
         * Restore original autocomplete and name value for prevent saving text in browser for unique value
         * @param $input
         */
        returnAttrs: function ($input) {
            $input.attr('autocomplete', $input.attr('data-prev-autocomplete'));
            $input.removeAttr('data-prev-autocomplete');
            if ($input.attr('data-prev-name')) {
                $input.attr('name', $input.attr('data-prev-name'));
                $input.removeAttr('data-prev-name');
            }
        }
    };

    return {
        init: init
    }
})();
PreventFieldsAutofill.init();
.input {
  display: block;
  width: 90%;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.42857143;
  color: #555555;
  background-color: #fff;
  background-image: none;
  border: 1px solid #ccc;
  border-radius: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form action="#">
  <p>
    <label for="input-1">Firts name without autocomplete</label><br />
    <input id="input-1" class="input" type="text" name="first-name" autocomplete="off" placeholder="Firts name without autocomplete" />
  </p>
  <p>
    <label for="input-2">Firts name with autocomplete</label><br />
    <input id="input-2" class="input" type="text" name="first-name" autocomplete="given-name" placeholder="Firts name with autocomplete" />
  </p>
  <p>
    <button type="submit">Submit form</button>
  </p>
</form>

Simply try to put attribute autocomplete with value "off" to input type.

<input type="password" autocomplete="off" name="password" id="password" />
<input type="text" name="attendees" id="autocomplete-custom-append">

<script>
  /* AUTOCOMPLETE */

  function init_autocomplete() {

    if (typeof ($.fn.autocomplete) === 'undefined') {
      return;
    }
    // console.log('init_autocomplete');

    var attendees = {
      1: "Shedrack Godson",
      2: "Hellen Thobias Mgeni",
      3: "Gerald Sanga",
      4: "Tabitha Godson",
      5: "Neema Oscar Mracha"
    };

    var countriesArray = $.map(countries, function (value, key) {
      return {
        value: value,
        data: key
      };
    });

    // initialize autocomplete with custom appendTo
    $('#autocomplete-custom-append').autocomplete({
      lookup: countriesArray
    });

  };
</script>
  1. Leave inputs with text type and hidden.
  2. On DOMContentLoaded, call a function that changes the types for password and display the fields, with a delay of 1s.

document.addEventListener('DOMContentLoaded', changeInputsType);

function changeInputsType() {
    setTimeout(function() {
        $(/*selector*/).prop("type", "password").show();
    }, 1000);
}

After trying all solutions (some have worked partly, disabling autofill but not autocomplete, some did not work at all), I've found the best solution as of 2020 to be adding type="search" and autocomplete="off" to your input element. Like this:

<input type="search" /> or <input type="search" autocomplete="off" />

Also make sure to have autocomplete="off" on the form element. This works perfectly and disables both autocomplete and autofill.

Also, if you're using type="email" or any other text type, you'll need to add autocomplete="new-email" and that will disable both perfectly. same goes for type="password". Just add a "new-" prefix to the autocomplete together with the type. Like this:

<input type="email" autocomplete="new-email" />
<input type="password" autocomplete="new-password" />

I already posted a solution for this here: Disable Chrome Autofill creditcard

The workaround is to set the autocomplete attribute as "cc-csc" that value is the CSC of a credit card and that they are no allowed to store it! (for now...)

autocomplete="cc-csc"

Simply change the name attribute in your input element to something unique each time and it will never autocomplete again!

An example might be a time tic added at the end. Your server would only need to parse the first part of the text name to retrieve the value back.

<input type="password" name="password_{DateTime.Now.Ticks}" value="" />

I've been fighting this never-ending battle for ages now... And all tricks and hacks eventually stop working, almost as if browser devs are reading this question.

I didn't want to randomize field names, touch the server-side code, use JS-heavy tricks and wanted to keep "hacks" to a minimum. So here's what I came up with:

TL;DR use an input without a name or id at all! And track changes in a hidden field

<!-- input without the "name" or "id" -->
<input type="text" oninput="this.nextElementSibling.value=this.value">
<input type="hidden" name="email" id="email">

Works in all major browsers, obviously.

P.S. Known minor issues:

  1. you can't reference this field by id or name anymore. But you can use CSS classes. Or use $(#email').prev(); in jQuery. Or come up with another solution (there's many).
  2. oninput and onchange events do not fire when the textbox value is changed programmatically. So modify your code accordingly to mirror changes in the hidden field too.

Since the behavior of autocomplete is pretty much unpredictable over different browsers and versions, my approach is a different one. Give all input elements for which you want to disable autofill the readonly attribute and only disable it on focus.

  document.addEventListener('click', (e) => {
    readOnlys.forEach(readOnly => {
      if (e.target == readOnly) {
        readOnly.removeAttribute('readonly', '');
        readOnly.style.setProperty('pointer-events', 'none');
      } else {
        readOnly.setAttribute('readonly', '');
        readOnly.style.setProperty('pointer-events', 'auto');
      }
    });
  });
  document.addEventListener('keyup', (e) => {
    if (e.key == 'Tab') {
      readOnlys.forEach(readOnly => {
        if (e.target == readOnly) {
          readOnly.removeAttribute('readonly', '');
          readOnly.style.setProperty('pointer-events', 'none');
        } else {
          readOnly.setAttribute('readonly', '');
          readOnly.style.setProperty('pointer-events', 'auto');
        }
      });
    }
  });

If you want to make sure that users can still access the fields if they have disabled JS, you can set all readonlys initially via JS on page load. You can still use the autocomplete attribute as a fallback.

You can add a name in attribute name how email address to your form and generate an email value. For example:

<form id="something-form">
  <input style="display: none" name="email" value="randomgeneratevalue"></input>
  <input type="password">
</form>

If you use this method, Google Chrome can't insert an autofill password.

Just autocomplete="off" list="autocompleteOff" in your input and work done for IE/Edge! and for chrome add autocomplete="new password"

I was fighting to autocomplete for years. I've tried every single suggestion, and nothing worked for me. Adding by jQuery 2 attributes worked well:

$(document).ready( function () {
    setTimeout(function() {
        $('input').attr('autocomplete', 'off').attr('autocorrect', 'off');
    }, 10);
}); 

will result in HTML

<input id="start_date" name="start_date" type="text" value="" class="input-small hasDatepicker" autocomplete="off" placeholder="Start date" autocorrect="off">

This works with Chrome 84.0.4147.105

1. Assign text type to password fields and add a class, e.g. "fakepasswordtype"

<input type="text" class="fakepasswordtype" name="password1">
<input type="text" class="fakepasswordtype" name="password2">

2. Then use jQuery to change the type back to password the moment when first input is done

jQuery(document).ready(function($) {
    $('.fakepasswordtype').on('input', function(e){
        $(this).prop('type', 'password');
    });
});

This stopped Chrome from its nasty ugly behavior from auto filling.

Chrome keeps trying to force autocomplete. So there are a few things you need to do.

The input field's attributes id and name need to not be recognizable. So no values such as name, phone, address, etc.

The adjacent label or div also needs to not be recognizable. However, you may wonder, how will the user know? Well there is a fun little trick you can do with ::after using the content. You can set it to a letter.

<label>Ph<span class='o'></span>ne</label>
<input id='phnbr' name='phnbr' type='text'>

<style>
  span.o {
    content: 'o';
  }
</style>

DO NOT USE JAVASCRIPT to fix this!!

Use HTML to address this problem first, in case browsers are not using scripts, fail to use your version of script, or have scripts turned off. Always layer scripting LAST on top of HTML.

  1. For regular input form fields with "text" type attributes, add the autocomplete="off" on the element. This may not work in modern HTML5 browsers due to user browser override settings but it takes care of many older browsers and stops the autocomplete drop down choices in most. Notice, I also include all the other autocomplete options that might be irritating to users, like autocapitalize="off", autocorrect="off", and spellcheck="false". Many browser do not support these but they add extra "offs" of features that annoy data entry people. Note that Chrome for example ignores "off" if a users browsers are set with autofill enabled. So, realize browser settings can override this attribute.

EXAMPLE:

<input type="text" id="myfield" name="myfield" size="20" value="" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" tabindex="0" placeholder="Enter something here..." title="Enter Something" aria-label="Something" required="required" aria-required="true" />
  1. For username and password input type fields, there are some limited browser support for more specific attributes for autocomplete that trigger the "off" feature". autocomplete="username" on text inputs used for logins will force some browsers to reset and remove the autocomplete feature. autocomplete="new-password" will try and do the same for passwords using the "password" type input field. (see below). However, these are propriety to specific browsers, and will fail in most. Browsers that do not support these features include Internet Explorer 1-11, many Safari and Opera desktop browsers, and some version of iPhone and Android default browsers. But they provide additional power to try and force removal of autocomplete.

EXAMPLE:

<input type="text" id="username" name="username" size="20" value="" autocomplete="username" autocapitalize="off" autocorrect="off" spellcheck="false" tabindex="0" placeholder="Enter username here..." title="Enter Username" aria-label="Username" required="required" aria-required="true" />
<input type="password" id="password" name="password" size="20" minlength="8" maxlength="12" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,12}" value="" autocomplete="new-password" autocapitalize="off" autocorrect="off" spellcheck="false" tabindex="0" placeholder="Enter password here..." title="Enter Password: (8-12) characters, must contain one number, one uppercase and lowercase letter" aria-label="Password" required="required" aria-required="true" />

NOW FOR A BETTER SOLUTION!

Because of the splintered support for HTML5 by standards bodies and browsers, many of these modern HTML5 attributes fail in many browsers. So, some kids turn to scripting to fill in the holes. But that's lazy programming. Hiding or rewriting HTML using JavaScript makes things worse, as you now have layers upon layers of script dependencies PLUS the HTML patches. Avoid this!

The best way to permanently disable this feature in forms and fields is to simply create a custom "id"/"name" value each time on your 'input' elements using a unique value like a date or time concatenated to the field id and name attribute and make sure they match (e.g. "name=password_{date}").

<input type="text" id="password_20211013" name="password_20211013" />

This destroys the silly browser autocomplete choice algorithms sniffing for matched names that trigger past values for these fields. Doing so, the browsers cannot match caches of previous form data with yours. It will force "autocomplete" to be off, or show a blank list, and will not show any previous passwords ever again! On the server side, you can create these custom input "named" fields and can still identify and extract the right field from the response coming from the user's browser by simply parsing the first part of the id/name. For example "password_" or "username_", etc. When the field's "name" value comes in you simply parse for the first part ("password_{date}") and ignore the rest, then extract your value on the server.

Easy!

Very simple solution Just change the label name and fields name other than the more generic name e.g: Name, Contact, Email. Use "Mail To" instead of "Email". Browsers ignore autocomplete off for these fields.

Define input's attribute type="text" along with autocomplete="off" works enough to turn off autocomplete for me.

EXCEPT for type="password", I try switching the readonly attribute using JavaScript hooking on onfocus/onfocusout event from others' suggestions works fine BUT while the password field editing begin empty, autocomplete password comes again.

I would suggest switching the type attribute regarding length of password using JavaScript hooking on oninput event in addition to above workaround which worked well..

<input id="pwd1" type="text" autocomplete="off" oninput="sw(this)" readonly onfocus="a(this)" onfocusout="b(this)" />
<input id="pwd2" type="text" autocomplete="off" oninput="sw(this)" readonly onfocus="a(this)" onfocusout="b(this)" />

and JavaScript..

function sw(e) {
    e.setAttribute('type', (e.value.length > 0) ? 'password' : 'text');
}
function a(e) {
    e.removeAttribute('readonly');
}
function b(e) {
    e.setAttribute('readonly', 'readonly');
}

Browser ignores autocomlete on readonly fields. This code makes all writable filds readonly till it's focused.

$(_=>{$('form[autocomplete=off] [name]:not([readonly])').map((i,t)=>$(t).prop('autocomplete',t.type=='password'?'new-password':'nope').prop('readonly',!0).one('focus',e=>$(t).prop('readonly',!1)));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" autocomplete="off">
<input name="user" id="user" required class="form-control" />
<label class="form-label" for="user">New User</label>
<hr>
<input type="password" name="pass" id="pass" minlength="8" maxlength="20" />
<label class="form-label" for="pass">New Passwort</label>
</form>

I was looking arround to find a solution to this but none of them worked proberly on all browsers.

I tried autocomplete off, none, nope, new_input_64, (even some funny texts) because the autoComplete attribute expects a string to be passed, no matter what.

After many searches and attempts I found this solution.

I changed all input types to text and added a bit of simple CSS code.

Here is the form:

<form class="row gy-3">
  <div class="col-md-12">
    <label for="fullname" class="form-label">Full Name</label>
    <input type="text" class="form-control" id="fullname" name="fullname" value="">
  </div>
  <div class="col-md-6">
    <label for="username" class="form-label">User Name</label>
    <input type="text" class="form-control" id="username" name="username" value="">
  </div>
  <div class="col-md-6">
    <label for="email" class="form-label">Email</label>
    <input type="text" class="form-control" id="email" name="email" value="">
  </div>
  <div class="col-md-6">
    <label for="password" class="form-label">Password</label>
    <input type="text" class="form-control pswd" id="password" name="password" value="">
  </div>
  <div class="col-md-6">
    <label for="password" class="form-label">Confirm Password</label>
    <input type="text" class="form-control pswd" id="password" name="password" value="">
  </div>
  <div class="col-md-12">
    <label for="recaptcha" class="form-label">ReCaptcha</label>
    <input type="text" class="form-control" id="recaptcha" name="recaptcha" value="">
  </div>
</form>

The CSS code to hide password:

.pswd {
    -webkit-text-security: disc;
}

Tested on Chrome, Opera, Edge.

This will fix this problem

autocomplete="new-password"

2022 September

Some browsers such as Google Chrome does not even care the value of autocomplete attribute. The best way to stop getting suggestions is changing the name attribute of the input to something that changes time to time

As of September 2022, browsers will not provide autocomplete for one time passwords

So we can use otp as the field name.

<input name="otp">

I was having trouble on a form which included input fields for username and email with email being right after username. Chrome would autofill my current username for the site into the email field and put focus on that field. This wasn't ideal as it was a form for adding new users to the web application.

It seems that if you have two inputs one after the other where the first one has the term 'user name' or username in it's label or ID and the next one has the word email in it's label or ID chrome will autofill the email field.

What solved the issue for me was to change the ID's of the inputs to not include those words. I also had to set the text of the labels to an empty string and use a javascript settimeout function to change the label back to what it should be after 0.01s.

setTimeout(function () { document.getElementById('id_of_email_input_label').innerHTML = 'Email:'; }, 10);

If you are having this problem with any other input field being wrongly autofilled I'd try this method.

Related