Firefox 在重新加载时保留表单数据

我对 Firefox 中保存用户在重新加载 F5时填写的数据的功能有一个很大的问题。如果我使用 Ctrl + F5的形式是明确的,这是伟大的。我的问题是,并不是所有的用户都知道这是他们必须做的,以强制输入清理。有没有办法在 html 或响应头中告诉 Firefox 不要将数据保存在表单中?

35743 次浏览

Just add autocomplete="off" to your inputs and you will solve the problem.

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

jQuery to solve this on all inputs and textareas

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

I think easier and quicker way to do that is

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

I tried the shortened solution above, but it didn't clear the value of the select boxes on my page.

I ended up modifying it slightly and now all input types on the page are cleared regardless of type:

var allInputs = $(":input");
$(allInputs).attr('autocomplete', 'off');

So to make this run onload I just put it in the ready() method:

$(document).ready(function () {
var allInputs = $(":input");
$(allInputs).attr('autocomplete', 'off');
});

Instead of going through all inputs you may also just add the attribute to your form-element like so:

<form method="post" autocomplete="off">...</form>

However the above mentioned methods on domReady did not work for me...

/*reset form elements (firefox saves it)*/


function resetElements()
{
var inputs = document.querySelectorAll('input[type=text]');
//you get the idea.....you can retrieve all inputs by tag name input
for(var i = 0; i < inputs.length; i++) {
document.getElementsByTagName('input')[i].value = "";
}
var textareas = document.getElementsByTagName('textarea');
for(var i = 0; i < textareas.length; i++) {
document.getElementsByTagName('textarea')[i].value = "";
}
}

Call this function onload.

In case you want to keep the autocomplete feature of the browser (see other valid answers), try adding the name attribute to the form and give it a random value. It has worked for me:

<form id="my-form" name="<random-hash>">
...
</form>

I found the only fix for me was to do

document.forms[0].reset();

before doc ready early in the page, as suggested in the comment by @Marek above - not great but worked for me (the autocomplete attribute method via either jQuery, JS or HTML didn't in the end fix it for me)

one of my colleagues recommended that we should use a random string as the name of the form. It works very well if you don't use the name attribute of the form.

it is an example from the sf1 form builder:

public function renderFormTag($url, array $attributes = [])
{
..
$attributes['name'] = isset($attributes['name']) ? $attributes['name'] : bin2hex(random_bytes(16));
..
}

just to piggyback on @jonnybradley's solution (couldn't comment on his answer because I don't have enough rep yet):

This also worked perfectly form me:

document.getElementById('theFormId').reset();

called after the HTML code.

autocomplete="off" is also needed for hidden input fields in order to have them refreshed on simple page reload (F5)