Trigger autocomplete without submitting a form

2019-01-06 11:17发布

问题:

I am writing a very simple web app with three text inputs. The inputs are used to generate a result, but all the work is done in Javascript, so there is no need to submit a form. I'm trying to find a way to get the browser to store input values for autocomplete as it would if they were in a form that was submitted.

I have tried giving the inputs autocomplete="on" manually, but without a form to submit, the browser has no way of knowing when it should store the values, so this has no effect.

I have also tried wrapping the inputs in a form that has onSubmit="return false;", but preventing the form from actually submitting appears to also prevent the browser from storing its inputs' values.

It is of course possible to manually use localStorage or a cookie to persist inputs and then generate autocomplete hints from those, but I'm hoping to find a solution that taps into native browser behavior instead of duplicating it by hand.

回答1:

Tested with Chrome, IE and Firefox:

<iframe id="remember" name="remember" class="hidden" src="/content/blank"></iframe>

<form target="remember" method="post" action="/content/blank">
  <fieldset>
    <label for="username">Username</label>
    <input type="text" name="username" id="username" value="">
    <label for="password">Password</label>
    <input type="password" name="password" id="password" value="">
  </fieldset>
  <button type="submit" class="hidden"></button>
</form>

In your Javascript trigger the submit, e.g. $("form").submit(); $("#submit_button").click() (updated from comments)

You need to return an empty page at /content/blank for get & post (about:blank didn't work for me but YMMV).



回答2:

We know that the browser saves its information only when the form is submitted, which means that we can't cancel it with return false or e.preventDefault()

What we can do is make it submit the data to nowhere without reloading a page. We can do that with an iframe

<iframe name="