How do you disable browser Autocomplete on web form field / input tag?

2008-08-06 html forms browser autocomplete

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

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" />

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.

<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.

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

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!"

Why would you make your user's life less convenient?

"Passwords / credit card data / etc. should not be saved" is a bad argument: with autocomplete on, browsers in Mac OS X store such values in an encrypted database with per-application permissions. Conversely, what's the realistic effect of autocomplete=off? The user is going to write it in an unencrypted text file, or better yet, on a post-it note attached to the screen.

Good thing there's bookmarklets like the one Antti mentioned, and patches to make the engine ignore the attribute altogether.

Seriously, I urge you to reconsider using this attribute. It does not benefit anyone.

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 info easily accessible. Of course, this was before the idea of private browsing that is starting to be featured in IE8, FF3.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.

In addition to autocomplete=off, you could also have your form fields 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.

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.

In order to avoid the invalid XHTML you can set this attribute using javascript. Example using jQuery:

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

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

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

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

I think autocomplete=off is supported in HTML 5.

Ask yourself why you want to do this though - it may make sense in some situations but don't do it just for the sake of doing it.

It's less convenient for users and not even a security issue in OS X (mentioned by Soren below). If you're worried about people having their passwords stolen remotely - a keystroke logger could still do it even though your app uses autcomplete=off.

As a user who chooses to have a browser remember (most of) my information, I'd find it annoying if your site didn't remember mine.

I'd have to beg to differ with those answers that say to avoid disabling auto-complete.

The first thing to bring up is that auto-complete not being explicitly disabled on login form fields is a PCI-DSS fail. In addition, if a users' local machine is compromised then any autocomplete data can be trivially obtained by an attacker due to it being stored in the clear.

There is certainly an argument for usability, however there's a very fine balance when it comes to which form fields should have autocomplete disabled and which should not.

You may use in input.

For example;

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

try these too if just autocomplete="off" doesn't work:

autocorrect="off" autocapitalize="off" autocomplete="off"

Three options: First:

<input type='text' autocomplete='off' />

Second:

<form action='' autocomplete='off'>

Third (javascript code):

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

None of the solutions worked for me in this conversation.

I finally figured out a pure HTML solution that requires no Javascript, works in modern browsers (except IE; there had to at least 1 catch, right?), and does not require you to disable autocomplete for the entire form.

Simply turn off autocomplete on the form and then turn it ON for any input you wish it to work within the form. For example:

<form autocomplete="off">
    <!-- these inputs will not allow autocomplete and chrome 
         won't highlight them yellow! -->
    <input name="username"  />
    <input name="password" type="password" />
    <!-- this field will allow autocomplete to work even 
         though we've disabled it on the form -->
    <input name="another_field" autocomplete="on" />
</form>

Most of the major browsers and password managers (correctly, IMHO) now ignore autocomplete=off.

Why? Many banks and other "high security" websites added autocomplete=off to their login pages "for security purposes" but this actually decreases security since it causes people to change the passwords on these high-security sites to be easy to remember (and thus crack) since autocomplete was broken.

Long ago most password managers started ignoring autocomplete=off, and now the browsers are starting to do the same for username/password inputs only.

Unfortunately, bugs in the autocomplete implementations insert username and/or password info into inappropriate form fields, causing form validation errors, or worse yet, accidentally inserting usernames into fields that were intentionally left blank by the user.

What's a web developer to do?

  • If you can keep all password fields on a page by themselves, that's a great start as it seems that the presence of a password field is the main trigger for user/pass autocomplete to kick in. Otherwise, read the tips below.
  • Safari notices that there are 2 password fields and disables autocomplete in this case, assuming it must be a change password form, not a login form. So just be sure to use 2 password fields (new and confirm new) for any forms where you allow
  • Chrome 34, unfortunately, will try to autofill fields with user/pass whenever it sees a password field. This is quite a bad bug that hopefully, they will change the Safari behavior. However, adding this to the top of your form seems to disable the password autofill:

    <input type="text" style="display:none">
    <input type="password" style="display:none">
    

I haven't yet investigated IE or Firefox thoroughly but will be happy to update the answer if others have info in the comments.

Sometimes even autocomplete=off would not prevent to fill in credentials into wrong fields, but not user or nickname field.

This workaround is in addition to apinstein's post about browser behavior.

fix browser autofill in read-only and set writable on focus (click and tab)

 <input type="password" readonly  
     onfocus="this.removeAttribute('readonly');"/>

Update: Mobile Safari sets cursor in the field, but does not show virtual keyboard. New Fix works like before but handles virtual keyboard:

<input id="email" readonly type="email" onfocus="if (this.hasAttribute('readonly')) {
    this.removeAttribute('readonly');
    // fix for mobile safari to show virtual keyboard
    this.blur();    this.focus();  }" />

Live Demo https://jsfiddle.net/danielsuess/n0scguv6/

// UpdateEnd

Because Browser auto fills credentials to wrong text field!?

I notice this strange behavior on Chrome and Safari, when there are password fields in the same form. I guess, the browser looks for a password field to insert your saved credentials. Then it auto fills (just guessing due to observation) the nearest textlike-input field, that appears prior the password field in DOM. As the browser is the last instance and you can not control it,

This readonly-fix above worked for me.

I've been trying endless solutions, and then I found this:

Instead of autocomplete="off" just simply use autocomplete="false"

As simple as that, and it works like a charm in Google Chrome as well!

This is a security issue that browsers ignore now. Browsers identify and stores content using input names, even if developers consider the information is sensitive and should not be stored. Making an input name different between 2 requests will solve the problem (but will still be saved in browser's cache and will also increase browser's cache). Ask the user to activate or deactivate options in its browser's settings is not a good solution. The issue can be fixed in the backend.

Here's my fix. An approach that I have implemented in my framework. All autocomplete elements are generated with an hidden input like this :

<? $r = rmd5(rand().mocrotime(TRUE)); ?>
<form method="POST" action="./">
    <input type="text" name="<? echo $r; ?>" />
    <input type="hidden" name="__autocomplete_fix_<? echo $r; ?>" value="username" />
    <input type="submit" name="submit" value="submit" />
</form>

Server then process post variables like this :

foreach ($_POST as $key => $val)
{
    if(preg_match('#^__autocomplete_fix_#', $key) === 1){
        $n = substr($key, 19);
        if(isset($_POST[$n]))$_POST[$val] = $_POST[$n];
    }
}

The value can be accessed as usual

var_dump($_POST['username']);

And the browser won't be able to suggest information from the previous request or from previous users.

All works like a charm, even if browsers updates, want to ignore autocomplete or not. That has been the best way to fix the issue for me.

None of the hacks mentioned here worked for me in Chrome. There's a discussion of the issue here: https://code.google.com/p/chromium/issues/detail?id=468153#c41

Adding this inside a <form> works (at least for now):

<div style="display: none;">
    <input type="text" id="PreventChromeAutocomplete" name="PreventChromeAutocomplete" autocomplete="address-level4" />
</div>

I know this is an old post, but it could be important to know that Firefox (I think only firefox) uses a value called ismxfilled that basically forces autocomplete.

ismxfilled="0" for OFF

or

ismxfilled="1" for ON

Adding autocomplete="off" is not gonna cut it.

Change input type attribute to type="search".
Google doesn't apply auto-fill to inputs with a type of search.

Safari does not change its mind about autocomplete if you set autocomplete="off" dynamically from javascript. However it would respect if you do that on per-field basis.

$(':input', $formElement).attr('autocomplete', 'off');
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        try {
            $("input[type='text']").each(function(){
                           $(this).attr("autocomplete","off");
                        });
        }
        catch (e)
        { }
    });

</script>

Chrome is planning to support this.

For now the best suggestion is to use an input type that is rarely autocompleted.

chrome discussion

<input type='search' name="whatever" />

to be compatible with firefox, use normal autocomplete='off'

<input type='search' name="whatever" autocomplete='off' />

You can disable autocomplete if you remove the form tag, the same was done by my bank and I was wondering how they did this. It even remove the value that was already remembered by the browser after you remove the tag.

This is what we called autocomplete of a textbox. enter image description here We can disable autocomplete of a Textbox in 2 ways-

  1. By Browser Label
  2. By Code

    To disable in browser go to the setting

    To dissable in browse go to the setting

Go to advance setting and uncheck the checkbox and then Restore.

Go to advance setting and uncheck the checkbox and then Restore.

If you want to disable in coding label you can do as follow-
Using AutoCompleteType="Disabled":

<asp:TextBox runat="server" ID="txt_userid" AutoCompleteType="Disabled"></asp:TextBox>  

By Setting Form autocomplete="off":

<asp:TextBox runat="server" ID="txt_userid" autocomplete="off"></asp:TextBox> 

By Setting Form autocomplete="off":

<form id="form1" runat="server" autocomplete="off">  
    //your content
</form>  

By using code in .cs page

protected void Page_Load(object sender, EventArgs e)  
    {  
    if(!Page.IsPostBack)  
    {  


        txt_userid.Attributes.Add("autocomplete", "off");  

    }  
}  

By Using Jquery

head runat="server">  
<title></title>  
<script src="Scripts/jquery-1.6.4.min.js"></script>  
<script type="text/javascript">  
    $(document).ready(function () {  
        $('#txt_userid').attr('autocomplete', 'off');  

    });  

</script>  

A little late to the game...but I just ran into this problem and tried several failures, but this one works for me found on MDN

In some case, the browser will keep suggesting autocompletion values even if the autocomplete attribute is set to off. This unexpected behavior can be quite puzzling for developers. The trick to really force the no-completion is to assign a random string to the attribute like so :

autocomplete="nope"

I can't believe this is still an issue so long after it's been reported. The above solutions didn't work for me, as safari seemed to know when the element was not displayed or off-screen, however the following did work for me:

<div style="height:0px; overflow:hidden; ">
  Username <input type="text" name="fake_safari_username" >
  Password <input type="password" name="fake_safari_password">
</div>

Hope that's useful for somebody!

If your issue is having a password field being auto-completed, then you may find this useful...

We had this issue in several areas of our site where the business wanted to re-query the user for their username and password and specifically did not want the password autofill to work for contractual reasons. We found that the easiest way to do this is to put in a fake password field for the browser to find and fill while the real password field remains untouched.

<!-- This is a fake password input to defeat the browser's autofill behavior -->
<input type="password" id="txtPassword" style="display:none;" />
<!-- This is the real password input -->
<input type="password" id="txtThisIsTheRealPassword" />

Note that in Firefox and IE, it was simply enough to put any input of type password before the actual one but Chrome saw through that and forced me to actually name the fake password input (by giving it an obvious password id) to get it to "bite". I used a class to implement the style instead of using an embedded style so try that if the above doesn't work for some reason.

You can simply put the autocomplete="off" in the HTML fields like following code.

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

So here is it:

function turnOnPasswordStyle() {
  $('#inputpassword').attr('type', "password");
}
<input oninput="turnOnPasswordStyle()" id="inputpassword" type="text">

The answer dsuess posted with the readonly was very clever and worked. But as I am using boostrap, the readonly input field was - until focused - marked with grey background. While the document loads, you can trick the browser by simply locking and unlocking the input.

So I had an idea to implement this into jQuery solution:

    jQuery(document).ready(function () {
        $("input").attr('readonly', true);
        $("input").removeAttr('readonly');
   });

My problem was mostly autofill with Chrome, but I think this is probably more problematic than autocomplete.

Trick : using a timer to reset form and set password fields to blank. The 100ms duration seems to be minimal for it to work.

$(document).ready(function() {
    setTimeout(function() {
        var $form = $('#formId');
        $form[0].reset();
        $form.find('INPUT[type=password]').val('');
    }, 100);
});

I use the following jQuery snippet:

// Prevent input autocomplete
$.fn.preventAutocomplete = function() {
    this.each(function () {
        var $el = $(this);
        $el
            .clone(false, false)
            .insertBefore($el)
            .prop('id', '')
            .hide()
        ;
    });
};

And than just $('#login-form input').preventAutocomplete();

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 would like to clarify that this answer is for completeness sake and for community knowledge, by no means is it recommended.

With regards to Internet Explorer 11, there is a security feature in place that can be used to block autocomplete. It works like this:

Any form input value that is modified in JavaScript AFTER the user has already entered it is flagged as ineligible for autocomplete.

This feature is normally used to protect users from malicious websites that want to change your password after you enter it or the like.

However, you could insert a single special character at the beginning of a password string to block autocomplete. This special character could be detected and removed later on down the pipeline.

The solution for Chrome is to add autocomplete="new-password" to the input type password. Please check the Example below.

Example:

<form name="myForm"" method="post">
   <input name="user" type="text" />
   <input name="pass" type="password" autocomplete="new-password" />
   <input type="submit">
</form>

Chrome always autocomplete the data if it finds a box of type password, just enough to indicate for that box autocomplete = "new-password".

This works well for me.

Note: make sure with F12 that your changes take effect, many times browsers save the page in cache, this gave me a bad impression that it did not work, but the browser did not actually bring the changes.

This works for me.

<input name="pass" type="password" autocomplete="new-password" />

We can also use this strategy in other controls like text, select etc

It doesn't seem to be possible to achieve this without using a combination client side and server side code.

In order to make sure that the user must fill in the form every time without autocomplete I use the following techniques:

  1. Generate the form field names on the server and use hidden input fields to store those names, so that when submitted to the server the server side code can use the generated names to access the field values. This is to stop the user from having the option to auto populate the fields.

  2. Place three instances of each form field on the form and hide the first and last fields of each set using css and then disable them after page load using javascript. This is to prevent the browser from filling in the fields automatically.

Here is a fiddle that demonstrates the javascript, css and html as described in #2 https://jsfiddle.net/xnbxbpv4/

javascript:

$(document).ready(function() {
    $(".disable-input").attr("disabled", "disabled");
});

css:

.disable-input {
  display: none;
}

html:

<form>
<input type="email" name="username" placeholder="username" class="disable-input">
<input type="email" name="username" placeholder="username">
<input type="email" name="username" placeholder="username" class="disable-input">
<br>
<input type="password" name="password" placeholder="password" class="disable-input">
<input type="password" name="password" placeholder="password">
<input type="password" name="password" placeholder="password" class="disable-input">
<br>
<input type="submit" value="submit">
</form>

Here is a rough example of what the server code using asp.net with razor would be to facilitate #1

model:

public class FormModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

controller:

public class FormController : Controller
{
    public ActionResult Form()
    {
        var m = new FormModel();

        m.Username = "F" + Guid.NewGuid().ToString();
        m.Password = "F" + Guid.NewGuid().ToString();

        return View(m);
    }

    public ActionResult Form(FormModel m)
    {
        var u = Request.Form[m.Username];
        var p = Request.Form[m.Password];

        // todo: do something with the form values

        ...

        return View(m);
    }
}

view:

@model FormModel

@using (Html.BeginForm("Form", "Form"))
{
    @Html.HiddenFor(m => m.UserName)
    @Html.HiddenFor(m => m.Password)

    <input type="email" name="@Model.Username" placeholder="username" class="disable-input">
    <input type="email" name="@Model.Username" placeholder="username">
    <input type="email" name="@Model.Username" placeholder="username" class="disable-input">
    <br>
    <input type="password" name="@Model.Password" placeholder="password" class="disable-input">
    <input type="password" name="@Model.Password" placeholder="password">
    <input type="password" name="@Model.Password" placeholder="password" class="disable-input">
    <br>
    <input type="submit" value="submit">
}

autocomplete = 'off' didn't work for me, anyway i set the value attribute of the input field to a space i.e <input type='text' name='username' value=" "> that set the default input character to a space, and since the username was blank the password was cleared too.

I use this TextMode="password" autocomplete="new-password" and in in page load in aspx txtPassword.Attributes.Add("value", '');

Try this :

<input type='text' autocomplete='off' />

Use

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

in addition to autocomplete="off" 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.

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>

Many modern browsers do not support autocomplete="off" for login fields anymore. autocomplete="new-password" is wokring instead, more information MDN docs

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'
      ... 
    />

You can use autocomplete = off in input controls to avoid auto completion

For example:

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

if the above code doesn't works then try to add those attributes also

autocapitalize="off" autocomplete="off"

or

Change input type attribute to type="search". Google doesn't apply auto-fill to inputs with a type of search.

The best solution:

Prevent autocomplete username (or email) and password:

<input type="email" name="email"><!-- Can be type="text" -->
<input type="password" name="password" autocomplete="new-password">

Prevent autocomplete a field:

<input type="text" name="field" autocomplete="nope">

Explanation: autocomplete continues work in <input>, autocomplete="off" does not work, but you can change off to a random string, like nope.

Works in:

  • Chrome: 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63 and 64

  • Firefox: 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 and 58

My solution is Change the text inputs type dynamically using angular js directive and it works like charm

first add 2 hidden text fields

and just add a angular directive like this

 (function () {

    'use strict';

    appname.directive('changePasswordType', directive);

    directive.$inject = ['$timeout', '$rootScope',  '$cookies'];

    function directive($timeout,  $rootScope, $cookies) {
        var directive = {
            link: link,
            restrict: 'A'
        };

        return directive;

        function link(scope,element) {
            var process = function () {
                var elem =element[0];
                elem.value.length > 0 ? element[0].setAttribute("type", "password") :
                element[0].setAttribute("type", "text");
            }

            element.bind('input', function () {
                process();
            });

            element.bind('keyup', function () {
                process();
            });
        }
    }
})()

then use it in your text field where you need to prevent auto complete

    <input type="text" style="display:none">\\can avoid this 2 lines
    <input type="password" style="display:none">
    <input type="text"  autocomplete="new-password" change-password-type>

NB: dont forget to include jquery, and set type ="text" initially

No fake inputs, no javascript!

There is no way to disable autofill consistently across browsers. I have tried all the different suggestions and none of them work in all browsers. The only way is not using password input at all. Here's what I came up with:

<style type="text/css">
    @font-face {
        font-family: 'PasswordDots';
        src: url('text-security-disc.woff') format('woff');
        font-weight: normal;
        font-style: normal;
    }

    input.password {
        font-family: 'PasswordDots' !important;
        font-size: 8px !important;
    }
</style>

<input class="password" type="text" spellcheck="false" />

Download: text-security-disc.woff

Here's how my final result looks like:

Password Mask

The negative side effect is that it's possible to copy plain text from the input, though it should be possible to prevent that with some JS.

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.

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.

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">

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>

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.

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.

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 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, 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(/^[[email protected]#\$%&*-_]/)) {
        $(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 is no 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 is in an Authorized IP list.
  • If either the password or IP 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 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.
  • 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 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 re-displayed.

You can add name in attribute name how email address to you form and generate 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 autofill password.

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);
    });

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'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>

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 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

To avoid autocomplete add the autocomplete="off" to your html input property. Example:

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>

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

autocomplete="randomstring" or autocomplete="rutjfkde"

it automatically converts it to

autocomplete="off"

when input control receives the focus.

So, I did it using jQuery, 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. Hope it will be helpful for the community.

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.

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

<input type="password" autocomplete="off" name="password" id="password" />

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>

Off course, this idea could be used with other JS frameworks as well.

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

Solutions with "autocomplete" tag 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 password type on your page.

And this works.

chears

Related