Как отключить автозаполнение браузера в поле / теге ввода веб-формы?

Как отключить autocompleteв основных браузерах для конкретного input(или form field)?

30 ответов

  1. So here is it:

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

  2. Firefox 30 игнорирует autocomplete="off"пароли, предпочитая вместо этого запрашивать пользователя, должен ли пароль храниться на клиенте. Обратите внимание на следующий комментарий от 5 мая 2014:

    • Менеджер паролей всегда предлагает сохранить пароль. Пароли не сохраняются без разрешения пользователя.
    • Мы третий браузер для реализации этого изменения, после IE и Chrome.

    Согласно документации разработчика Mozilla атрибут элемента формы autocompleteпредотвращает кэширование данных формы в старых браузерах.

    <input type="text" name="foo" autocomplete="off" />
  3. Was a non-standard way to do this (I think Mozilla and Internet Explorer still support it) but messing with the users expectations is a bad idea.

    If the user enters their credit card details in a form and then let’s someone else use that browser it’s not your concern. 🙂

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

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

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

  7. 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
    . It removes
    all autocomplete="off" attributes from all forms on the page. Keep
    fighting the good fight!»

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

  9. Кроме тогоautocomplete=off, имена полей формы могут быть рандомизированы кодом, создающим страницу, возможно, путем добавления определенной для сеанса строки в конец имен.

    При отправке формы эту часть можно удалить перед обработкой на стороне сервера. Это предотвратит поиск веб-браузером контекста для поля, а также поможет предотвратить атаки XSRF, поскольку злоумышленник не сможет угадать имена полей для отправки формы.

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

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

  12. Adding the


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

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

  15. Three options:

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


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

    Third (javascript code):

    $('input').attr('autocomplete', 'off');
  16. 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" />
  17. Большинство основных браузеров и менеджеров паролей (правильно, IMHO) теперь игнорируют autocomplete=off.

    Почему? Многие банки и другие веб-сайты» высокой безопасности «добавлены autocomplete=offна свои страницы входа» в целях безопасности», но это на самом деле снижает безопасность, так как это заставляет людей менять пароли на этих сайтах высокой безопасности, чтобы быть легко запомнить (и, таким образом, взломать), так как автозаполнение было нарушено.

    Давно большинство менеджеров паролей начали игнорироватьautocomplete=off, и теперь браузеры начинают делать то же самое только для ввода имени пользователя/пароля.

    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 замечает, что есть 2 поля пароля и отключает автозаполнение в этом случае, предполагая, что это должна быть форма изменения пароля, а не форма входа в систему. Поэтому просто не забудьте использовать 2 поля пароля (new и confirm new) для любых форм, где вы позволяете
    • Chrome 34, К сожалению, будет пытаться автоматически заполнять поля с user / pass, когда он видит поле пароля. Это довольно плохая ошибка, которая, надеюсь, они изменят поведение Safari. Тем не менее, добавление этого в верхней части формы, кажется, отключить автозаполнение пароля:

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

    Я еще не исследовал IE или Firefox тщательно, но буду рад обновить ответ, если у других есть информация в комментариях.

  18. Иногда даже автозаполнение=off не помешает заполнить учетные данные в неправильные поля, но не поле пользователя или псевдонима.

    Этот обходной путь в дополнение к сообщению apinstein о поведении браузера.

    fix браузер автозаполнение в режиме только для чтения и установить запись на фокус (нажмите и вкладка)

     <input type="password" readonly  

    Mobile Safari устанавливает курсор в поле, но не показывает виртуальную клавиатуру. Новое исправление работает как раньше, но обрабатывает виртуальную клавиатуру:

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

    Живая демонстрация 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.

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

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

    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


    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.

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

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

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

    Hope that’s useful for somebody!

  24. The solution for Chrome is to add autocomplete="new-password" to the input type password.


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

    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.

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

  26. Try to add

    readonly onfocus=»this.removeAttribute(‘readonly’);»

    in addition to


    to the input(s) that you do not want 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');" >

    Update: Here is full example below based on this approach that prevents from drag & drop, copy, paste, etc.

    <input type="text" name="UserName" style="text-transform:lowercase;" placeholder="Username" 
        autocomplete="off" readonly onfocus="this.removeAttribute('readonly');" 
        oncopy="return false" ondrag="return false" ondrop="return false" 
        onpaste="return false" oncontextmenu="return false" > 
    <input type="password" name="Password" placeholder="Password" autocomplete="off" readonly 
        onfocus="this.removeAttribute('readonly');" oncopy="return false" ondrag="return false" 
        ondrop="return false" onpaste="return false" oncontextmenu="return false" >

    Tested on the latest versions of the major browsers i.e. Google Chrome, Mozilla Firefox, Microsoft Edge, etc. and working without any problem. Hope this helps…

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

    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

  28. I’ve solved the endless fight with Google Chrome with the use of random characters.

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

    Hope that it will help to other people.