- How to Disable the Browser Autocomplete and Autofill on HTML Form and Input Fields
- How to Disable Autocomplete
- Example of using the autocomplete attribute with the «off» value:
- Example of disabling the autocomplete:
- Example of removing the yellow background from the field:
- Example of disabling the autocomplete with Javascript:
- Example of disabling the autocomplete using Javascript:
- Example of disabling the autocomplete with jQuery:
- Example of disabling the autofill with jQuery:
- Как отключить автозаполнение форм с помощью html 5?
- Атрибут autocomplete
- Синтаксис
- Значения
- Обязательный атрибут
- Значение по умолчанию
How to Disable the Browser Autocomplete and Autofill on HTML Form and Input Fields
When a user starts typing in the HTML form field, browsers, by default, enable the autocomplete feature. Many users let their browsers collect form data allowing using autocomplete in forms in the future. However, there can be situations when this can not work accurately, or you might prefer that users manually insert all the information in details. Moreover, there might be a privacy concern for users, so browsers can let users disable it.
Some data presented in forms, however, are either not important in the future (such as a one-time pin) or include confidential information (such as a specific government identification or security code for bank cards). As the author of a website, you might prefer the browser not to remember the values for that kind of fields, even though the autocomplete feature of the browser is enabled. This allows the browser to offer autocompletion (i.e., display possible completions for the fields where the user has started typing) or autofill (i.e., pre-populate some fields on load).
How to Disable Autocomplete
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:
- Add autocomplete=»off» onto the element to disable autocomplete for the entire form.
- Add autocomplete=»off» for a specific element of the form.
The autocomplete attribute works with the following types: text, search, url, tel, email, password, datepickers, range, and color.
Let’s see an example where the autocomplete is set to «off» for the whole form and two elements.
Example of using the autocomplete attribute with the «off» value:
html> html> head> title>Title of the document title> style> input < margin: 5px 0; padding: 5px; > style> head> body> form action="/form/submit" method="get" autocomplete="off"> div> input type="text" name="Name" placeholder="First Name" autocomplete="off"> div> div> input type="text" id="lname" name="Surname" placeholder="Last Name" autocomplete="off"> div> div> input type="number" name="Credit card number" placeholder="Credit card number"> div> input type="submit" value="Submit"> form> body> html>
Let’s see another example. Here, you’ll need the following steps:
- Add autocomplete=»off» to the element.
- Add a hidden with autocomplete=»false» as a first child element of the form.
Example of disabling the autocomplete:
html> html> head> title>Title of the document title> style> input:not[type="submit"] < background-color: #ffffff; border: 1px solid #cccccc; padding: 5px; > input:-webkit-autofill < -webkit-box-shadow: 0 0 0 1000px white inset !important; > .hidden < display: none; > style> head> body> form autocomplete="off" method="post" action="/form/submit"> input autocomplete="false" name="hidden" type="text" class="hidden"> div> label for="name">Name input type="text" name="name" Id="name" placeholder="Enter Your Name"> label> div> br/> div> label for="email">Email input type="Email" name="email" Id="email" placeholder="Enter Your Email"> label> div> br/> input type="submit" value="Submit"> form> body> html>
There are two effects of setting autocomplete=»off » for your form fields:
- Tells the browser not to save user-input data on similar forms for later autocompletion, although browser-specific algorithms vary.
- Prevents the browser from caching form data in the session history. When the data of forms is stored in the session history, the information filled in by the user will be still displayed, even if the user has submitted the form and clicked the Back button to return to the initial form page.
As many users wouldn’t like the browser to remember passwords, modern browsers do not support the autocomplete=»off » for login fields. For login fields, there is no difference whether autocomplete is disabled for fields or fields.
When a website sets autocomplete=»off » for a or element, and username/password fields are included in it, the browser will still allow remembering these fields, and if the user accepts, the browser will autofill the fields the next time when the user visits that website.
In that way behave Firefox (since version 38), and Google Chrome (since version 34).
In the case, you represent a user management page where a user can specify a new password for a different user, and you don’t want to autofill password fields, use autocomplete=»new-password» , which is a sign for browsers that they are not required to react to it.
If Google Chrome remembers a login or password, it will change the background to yellow. To remove the background color, you can try the following.
Example of removing the yellow background from the field:
html> html> head> title>Title of the document title> style> input:-webkit-autofill < -webkit-box-shadow: 0 0 0 1000px white inset !important; > style> head> body> form action="/form/submit" method="GET"> div> label for="name">Name input type="text" name="name" Id="name" placeholder="Enter Your Name"> label> div> br/> div> label for="email">Email input type="email" name="email" Id="email" placeholder="Enter Your Email"> label> div> br/> input type="submit" value="Submit"> form> body> html>
There are some probably better ways of disabling the autocomplete and autofill with Javascript and jQuery. Let’s also see some examples with them before you can decide which is best for your code.
Example of disabling the autocomplete with Javascript:
html> html lang="en"> head> title>Title of the Document title> head> body> form action="/form/submit" method="post"> div class="form-group"> input type="text" name="username" placeholder="Enter Name"> input type="email" name="email" placeholder="Enter Email"> button type="submit"> Submit button> div> form> script> let tagArr = document.getElementsByTagName("input"); for (let i = 0; i < tagArr.length; i++) < tagArr[i].autocomplete = 'off'; > script> body> html>
Example of disabling the autocomplete using Javascript:
html> html lang="en"> head> title>Title of the Document title> script src="https://code.jquery.com/jquery-3.5.0.min.js"> script> head> body> form action="/form/submit" method="post"> div class="form-group"> input type="text" id="name" name="username" placeholder="Enter Name"> input type="email" id="email" name="email" placeholder="Enter Email"> button type="submit">Submit button> div> form> script> $(document).ready(function( ) < $('input').attr('autocomplete', 'off'); >); script> body> html>
Example of disabling the autocomplete with jQuery:
html> html lang="en"> head> title>Title of the Document title> script src="https://code.jquery.com/jquery-3.5.0.min.js"> script> head> body> form action="/form/submit" method="post"> div class="form-group"> input type="text" id="name" name="username" placeholder="Enter Name"> input type="email" id="email" name="email" placeholder="Enter Email"> button type="submit">Submit button> div> form> script> $(document).ready(function( ) < try < $("input[type='text']").each(function( ) < $(this).attr("autocomplete", "off"); >); > catch (e) <> >); script> body> html>
Example of disabling the autofill with jQuery:
html> html> head> title>Title of the document title> script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"> script> script src="https://terrylinooo.github.io/jquery.disableAutoFill/assets/js/jquery.disableAutoFill.min.js"> script> head> body> form action="/form/submit" method="post" id="login-form"> input name="username" type="text" placeholder="username" /> input name="password" type="password" placeholder="password" /> input type="submit" value="Submit"> form> script> $(function( ) < $('#login-form').disableAutoFill(); >); script> body> html>
Как отключить автозаполнение форм с помощью html 5?
Ничего не получается. На поле всё равно срабатывает авто заполнение.
Что я делаю не так?
UPD.
Оценить 1 комментарий
Миржалол Мирхомитов, Гениально! 04.09.2021 всё работает.
chrome Версия 92.0.4515.159 (Официальная сборка), (64 бит)
такие дела))
14.10.2021. Chrome Версия 94.0.4606.81 (Официальная сборка), (64 бит) до сих пор работает)
Очень простой и изящный способ как отключить автозаполнения и выпадающие списки с выбором логина и пароля от браузера на формах регистрации и прочих формах.
здесь мы отключаем автозаполнение пароля, а также чтобы не было выпадающего списка выбором паролей там где это не нужно:
— оборачиваем форму в блок со свойством position:relative
— после поля прописываем блок с position:absolute top:0 left:0 width:100% height:100%
— создаем событие onclick, для класса field где вызываем фокус для нашего поля внутри
До
После
Евгений Коелсник, akb2.
Можете подсказать, пж?
Я не совсем понял как нужно сделать, чтобы не было выпадающего списка выбором паролей.
Можно отключить автозаполнение, если в момент фокусировки в поле поменять у поля значение name на произвольное. А когда пользователь выходит из input, то поменять значение name обратно. В этом случае браузер Хром не выводит подсказок, т.к. каждый раз значение name новое.
Необходимо подключать jquery, а ниже подключить сам скрипт.
Исходник (взял отсюда только код, который генерит значение name) https://github.com/terrylinooo/jquery.disableAutoFill
Это сама форма, показываю кусок формы, с полями ввода, для которых отключаю подсказки хрома. Оба инпута имеют класс «only-ru»:
Сам скрипт, который при фокусе генерит произвольное значение для name, а при выходе из фокуса — возвращает значение name обратно, как мне нужно. Можете его улучить, сделать более универсальным:
//поменять name при фокусе $('.only-ru').on("focus", function()< var realFields = []; var realFieldsMapper = <>; $(this).each(function(i) < realFields[i] = $(this).attr('name'); if(realFieldsMapper[realFields[i]]) < $(this).attr('name', realFieldsMapper[realFields[i]]); >else < var randomName = Math.random().toString(36).replace(/[^a-z]+/g, ''); $(this).attr('name', randomName); realFieldsMapper[realFields[i]] = randomName; >>); >); //поменять name обратно $(document).mouseup(function (e)< var div1 = $("#city1"), div2 = $("#city2"); if (!div1.is(e.target)) $("input#city1").attr('name', 'city1'); if (!div2.is(e.target)) $("input#city2").attr('name', 'city2'); >);
Атрибут autocomplete
Управляет автозаполнением полей форм. Значение может быть перекрыто атрибутом autocomplete у конкретных элементов формы.
Автозаполнение производит браузер, который запоминает написанные при первом вводе значения, а затем подставляет их при повторном наборе в поля формы. При этом автозаполнение может быть отключено в настройках браузера и не может быть в таком случае изменено при помощи атрибута autocomplete . К примеру, включение автозаполнения в браузере Chrome показано на рис. 1.
Рис. 1. Настройки автозаполнения
При вводе первых букв текста отображается список сохранённых ранее значений, из которого можно выбрать необходимое (рис. 2).
Рис. 2. Список для подстановки
Синтаксис
Значения
on Включает автозаполнение формы. off Отключает автозаполнение. Это значение обычно используется для отмены сохранения в браузере важных данных (паролей, номеров банковских карт), а также редко вводимых или уникальных данных (капча).
Обязательный атрибут
Значение по умолчанию
Имя:
Пароль: