Html 在不提交表单的情况下触发自动完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15462991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:35:45  来源:igfitidea点击:

Trigger autocomplete without submitting a form

javascripthtmlforms

提问by AmericanUmlaut

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.

我正在编写一个非常简单的 Web 应用程序,其中包含三个文本输入。输入用于生成结果,但所有工作都是在 Javascript 中完成的,因此无需提交表单。我试图找到一种方法让浏览器存储自动完成的输入值,就像它们在提交的表单中一样。

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.

我试过手动输入 autocomplete="on" ,但没有提交表单,浏览器无法知道何时应该存储值,所以这没有效果。

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.

我还尝试将输入包装在具有 onSubmit="return false;" 的表单中,但阻止表单实际提交似乎也阻止了浏览器存储其输入的值。

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.

当然,可以手动使用 localStorage 或 cookie 来持久化输入,然后从中生成自动完成提示,但我希望找到一种解决方案,利用原生浏览器行为,而不是手动复制它。

采纳答案by laktak

Tested with Chrome, IE and Firefox:

用 Chrome、IE 和 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)

在您的 Javascript 中触发提交,例如 $("form").submit();$("#submit_button").click()(从评论更新)

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

您需要在 /content/blank 返回一个空页面以获取和发布(about:blank 对我不起作用,但 YMMV)。

回答by fregante

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

我们知道浏览器只有在提交表单时才会保存它的信息,这意味着我们不能用return false或取消它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

<iframe name="" style="display:none" src="about:blank"></iframe>

<form target="" action="about:blank">
    <input name="user">
    <input name="password" type="password">
    <input value="Login" type="submit">
</form>

Demo on JSfiddle (tested in IE9, Firefox, Chrome)

JSfiddle 上的演示(在 IE9、Firefox、Chrome 中测试)

Pros over the currently accepted answer:

目前接受的答案的优点:

  • shorter code;
  • no jQuery;
  • no server-side page loaded;
  • no additional javascript;
  • no additional classes necessary.
  • 较短的代码;
  • 没有 jQuery;
  • 没有加载服务器端页面;
  • 没有额外的javascript;
  • 不需要额外的课程。

There is no additional javascript. You normally attach an handler to the submitevent of the form to send the XHR and don't cancel it.

没有额外的javascript。您通常将处理程序附加到submit表单的事件以发送 XHR 并且不要取消它。

Javascript example

Javascript 示例

// for modern browsers with window.fetch
document.forms[0].addEventListener('submit', function (event) {
    fetch('login.php', {
        method: 'post',
        body: new FormData(event.target))
    }).then(r => r.text()).then(() => { /* login completed */ })
    // no return false!!
});

No-javascript support

无 javascript 支持

Ideally, you should let the form work without javascript too, so remove the targetand set the action to a page that will receive your form data.

理想情况下,您也应该让表单在没有 javascript 的情况下工作,因此删除target并将操作设置为将接收表单数据的页面。

<form action="login.php">

And then simply add it via javascript when you add the submitevent:

然后在添加submit事件时通过 javascript 添加它:

formElement.target = '';
formElement.action = 'about:blank';

回答by Alex

I haven't tested this, but it might work if you submit the form to a hidden iframe (so that the form is actually submitted but the current page is not reloaded).

我还没有测试过这个,但是如果您将表单提交到隐藏的 iframe(这样表单实际上已提交但当前页面不会重新加载),它可能会起作用。

<iframe name="my_iframe" src="about:blank"></iframe>

<form target="my_iframe" action="about:blank" method="get">...</form>

回答by IJMorgado

Maybe you can use this Twitter Typeahead...is a very complete implementation of a autocomplete, with local and remote prefetch, and this make use of localStorage to persist results and also it show a hint in the input element...the code is easy to understand and if you don't want to use the complete jquery plugin, I think you can take a look of the code to see how to achieve what you want...

也许你可以使用这个Twitter Typeahead......是一个非常完整的自动完成实现,具有本地和远程预取,这利用 localStorage 来持久化结果,并在输入元素中显示一个提示......代码是易于理解,如果您不想使用完整的 jquery 插件,我想您可以查看代码以了解如何实现您想要的...

回答by aIKid

From what i searched.. it seems you need to identify the names. Some standard names like 'name', 'email', 'phone', 'address' are automatically saved in most browser.

从我搜索的内容来看……看来您需要确定名称。大多数浏览器会自动保存一些标准名称,如“姓名”、“电子邮件”、“电话”、“地址”。

Well, the problem is, browsers handle these names differenetly. For example, here is chrome's regex:

好吧,问题是,浏览器以不同的方式处理这些名称。例如,这是 chrome 的正则表达式:

  • first name: "first.*name|initials|fname|first$"
  • email: "e.?mail"
  • address (line 1): "address.*line|address1|addr1|street"
  • zipcode: "zip|postal|post.*code|pcode|^1z$"
  • 名字:“first.*name|姓名首字母|fname|first$”
  • 电子邮件:“e.?mail”
  • 地址(第 1 行):“address.*line|address1|addr1|street”
  • 邮政编码:“zip|postal|post.*code|pcode|^1z$”

But chrome also uses autocomplete, so you can customize the name and put an autocomplete type, but i believe this is not for custom fields..

但是 chrome 也使用autocomplete,因此您可以自定义名称并放置自动完成类型,但我相信这不适用于自定义字段..

Here is chrome's standard

这是 chrome 的标准

And it's another thing in IE, Opera, and Mozilla. For now, you can try the iframe solution there, so you can submit it. (Maybe it's something semi-standard)

这是 IE、Opera 和 Mozilla 中的另一件事。现在,您可以在那里尝试 iframe 解决方案,以便您可以提交它。(也许这是半标准的东西)

Well, that's all i can help.

嗯,我能帮到的就这些了。

回答by Carter Medlin

For those who would rather not change their existing form functionality, you can use a second form to receive copies of all the form values and then submit to a blank page before your main form submits. Here is a fully testable HTML document using JQuery Mobile demonstrating the solution.

对于那些不想更改现有表单功能的人,您可以使用第二个表单来接收所有表单值的副本,然后在提交主表单之前提交到空白页面。这是一个使用 JQuery Mobile 演示解决方案的完全可测试的 HTML 文档。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
    <form method="post">
        <input type="text" name="email" />
        <input type="submit" value="GO" onclick="save_autofill(this);" />
    </form>


    <script>
        function save_autofill(o) {
            $(':input[name]', $('#hidden_form')).val(function () {
                return $(':input[name=' + this.name + ']', $(o.form)).val();
            });

            $('#hidden_form').find("input[type=submit]").click();
        }
    </script>

    <iframe name="hidden_iframe" style="display:none"></iframe>
    <form target="hidden_iframe" id="hidden_form" action="about:blank" style="display:none">
        <input type="text" name="email" />
        <input type="submit" />
    </form>
</body>
</html>

The save_autofillfunction just needs to be called on your main form submit button. If you have a scripted function that submits your form, place that call after the save_autofillcall. You must have a named textbox in your hidden_formfor each one in your main form.

save_autofill函数只需要在您的主表单提交按钮上调用。如果您有提交表单的脚本化函数,请在调用之后进行save_autofill调用。您hidden_form的主表单中的每个文本框都必须有一个命名文本框。

If your site uses SSL, then you must change the URL for about:blankwith https://about:blank.

如果您的站点使用 SSL,则您必须更改about:blankwith的 URL https://about:blank

回答by pravchuk

---WITHOUT IFRAME---

---没有 IFRAME---

Instead of using iframe, you can use action="javascript:void(0)", this way it doesn't go to another page and autocomplete will store the values.

您可以使用 action="javascript:void(0)" 而不是使用 iframe,这样它就不会转到另一个页面并且自动完成将存储这些值。

<form action="javascript:void(0)">
    <input type="text" name="firstName" />
    <button type="submit">Submit</button>
</form>

回答by Prakash Bhagat

You can use jQuery to persist autocomplete data in the localstorage when focusout and when focusin it autocompletes to the value persisted.

您可以使用 jQuery 将自动完成数据保存在 localstorage 中,当 focusout 和当 focusin 自动完成到持久化的值时。

i.e.

IE

$(function(){
 $('#txtElement').on('focusout',function(){
   $(this).data('fldName',$(this).val());
 }

 $('#txtElement').on('focusin',function(){
   $(this).val($(this).data('fldName'));
 }
}

You can also bind persistence logic on other events also depending on the your application requirement.

您还可以根据您的应用程序要求在其他事件上绑定持久性逻辑。

回答by max zhou

you can use "." in both iframe src and form action.

您可以使用 ”。” 在 iframe src 和表单操作中。

 <iframe id="remember" name="remember" style="display:none;" src="."></iframe>
 <form target="remember" method="post" action=".">
    <input type="text" id="path" size='110'>
    <button type="submit" onclick="doyouthing();">your button</button>
</form>

回答by garageàtrois

Make sure you're submitting the form via POST. If you're submitting via ajax, do <form autocomplete="on" method="post">, omitting the actionattribute.

确保您通过 POST 提交表单。如果您通过 ajax 提交,请<form autocomplete="on" method="post">省略该action属性。