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